App.py 454 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143
  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, color_variant, ExclusionAreas
  38. from Bookmark import BookmarkManager
  39. from AppDatabase import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from AppObjects.ObjectCollection import *
  47. from AppObjects.FlatCAMObj import FlatCAMObj
  48. from AppObjects.AppObject import AppObject
  49. # FlatCAM Parsing files
  50. from AppParsers.ParseExcellon import Excellon
  51. from AppParsers.ParseGerber import Gerber
  52. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  53. # FlatCAM AppGUI
  54. from AppGUI.PlotCanvas import *
  55. from AppGUI.PlotCanvasLegacy import *
  56. from AppGUI.MainGUI import *
  57. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  58. # FlatCAM Pre-processors
  59. from AppPreProcessor import load_preprocessors
  60. # FlatCAM AppEditors
  61. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  62. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  63. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  64. from AppEditors.FlatCAMTextEditor import TextEditor
  65. from AppParsers.ParseHPGL2 import HPGL2
  66. # FlatCAM Workers
  67. from AppProcess import *
  68. from AppWorkerStack import WorkerStack
  69. # FlatCAM Tools
  70. from AppTools import *
  71. # FlatCAM Translation
  72. import gettext
  73. import AppTranslation as fcTranslate
  74. import builtins
  75. if sys.platform == 'win32':
  76. import winreg
  77. from win32comext.shell import shell, shellcon
  78. fcTranslate.apply_language('strings')
  79. if '_' not in builtins.__dict__:
  80. _ = gettext.gettext
  81. class App(QtCore.QObject):
  82. """
  83. The main application class. The constructor starts the AppGUI.
  84. """
  85. # ###############################################################################################################
  86. # ########################################## App ################################################################
  87. # ###############################################################################################################
  88. # ###############################################################################################################
  89. # ######################################### LOGGING #############################################################
  90. # ###############################################################################################################
  91. log = logging.getLogger('base')
  92. log.setLevel(logging.DEBUG)
  93. # log.setLevel(logging.WARNING)
  94. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  95. handler = logging.StreamHandler()
  96. handler.setFormatter(formatter)
  97. log.addHandler(handler)
  98. # ###############################################################################################################
  99. # #################################### Get Cmd Line Options #####################################################
  100. # ###############################################################################################################
  101. cmd_line_shellfile = ''
  102. cmd_line_shellvar = ''
  103. cmd_line_headless = None
  104. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  105. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  106. "FlatCam.py --headless=1"
  107. try:
  108. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  109. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  110. "shellvar=",
  111. "headless=",
  112. "multiprocessing-fork="])
  113. except getopt.GetoptError:
  114. print(cmd_line_help)
  115. sys.exit(2)
  116. for opt, arg in cmd_line_options:
  117. if opt == '-h':
  118. print(cmd_line_help)
  119. sys.exit()
  120. elif opt == '--shellfile':
  121. cmd_line_shellfile = arg
  122. elif opt == '--shellvar':
  123. cmd_line_shellvar = arg
  124. elif opt == '--headless':
  125. try:
  126. cmd_line_headless = eval(arg)
  127. except NameError:
  128. pass
  129. # ###############################################################################################################
  130. # ################################### Version and VERSION DATE ##################################################
  131. # ###############################################################################################################
  132. version = 8.993
  133. version_date = "2020/08/01"
  134. beta = True
  135. engine = '3D'
  136. # current date now
  137. date = str(datetime.today()).rpartition('.')[0]
  138. date = ''.join(c for c in date if c not in ':-')
  139. date = date.replace(' ', '_')
  140. # ###############################################################################################################
  141. # ############################################ URLS's ###########################################################
  142. # ###############################################################################################################
  143. # URL for update checks and statistics
  144. version_url = "http://flatcam.org/version"
  145. # App URL
  146. app_url = "http://flatcam.org"
  147. # Manual URL
  148. manual_url = "http://flatcam.org/manual/index.html"
  149. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  150. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  151. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  152. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  153. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  154. # this variable will hold the project status
  155. # if True it will mean that the project was modified and not saved
  156. should_we_save = False
  157. # flag is True if saving action has been triggered
  158. save_in_progress = False
  159. # ###############################################################################################################
  160. # ####################################### APP Signals ######################################################
  161. # ###############################################################################################################
  162. # Inform the user
  163. # Handled by:
  164. # * App.info() --> Print on the status bar
  165. inform = QtCore.pyqtSignal(str)
  166. app_quit = QtCore.pyqtSignal()
  167. # General purpose background task
  168. worker_task = QtCore.pyqtSignal(dict)
  169. # File opened
  170. # Handled by:
  171. # * register_folder()
  172. # * register_recent()
  173. # Note: Setting the parameters to unicode does not seem
  174. # to have an effect. Then are received as Qstring
  175. # anyway.
  176. # File type and filename
  177. file_opened = QtCore.pyqtSignal(str, str)
  178. # File type and filename
  179. file_saved = QtCore.pyqtSignal(str, str)
  180. # Percentage of progress
  181. progress = QtCore.pyqtSignal(int)
  182. # Emitted when a new object has been added or deleted from/to the collection
  183. object_status_changed = QtCore.pyqtSignal(object, str, str)
  184. message = QtCore.pyqtSignal(str, str, str)
  185. # Emmited when shell command is finished(one command only)
  186. shell_command_finished = QtCore.pyqtSignal(object)
  187. # Emitted when multiprocess pool has been recreated
  188. pool_recreated = QtCore.pyqtSignal(object)
  189. # Emitted when an unhandled exception happens
  190. # in the worker task.
  191. thread_exception = QtCore.pyqtSignal(object)
  192. # used to signal that there are arguments for the app
  193. args_at_startup = QtCore.pyqtSignal(list)
  194. # a reusable signal to replot a list of objects
  195. # should be disconnected after use so it can be reused
  196. replot_signal = pyqtSignal(list)
  197. # signal emitted when jumping
  198. jump_signal = pyqtSignal(tuple)
  199. # signal emitted when jumping
  200. locate_signal = pyqtSignal(tuple, str)
  201. # close app signal
  202. close_app_signal = pyqtSignal()
  203. # will perform the cleanup operation after a Graceful Exit
  204. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  205. # graphic residues behind
  206. cleanup = pyqtSignal()
  207. def __init__(self, user_defaults=True):
  208. """
  209. Starts the application.
  210. :return: app
  211. :rtype: App
  212. """
  213. super().__init__()
  214. App.log.info("FlatCAM Starting...")
  215. self.main_thread = QtWidgets.QApplication.instance().thread()
  216. # ############################################################################################################
  217. # ################# Setup the listening thread for another instance launching with args ######################
  218. # ############################################################################################################
  219. if sys.platform == 'win32' or sys.platform == 'linux':
  220. # make sure the thread is stored by using a self. otherwise it's garbage collected
  221. self.th = QtCore.QThread()
  222. self.th.start(priority=QtCore.QThread.LowestPriority)
  223. self.new_launch = ArgsThread()
  224. self.new_launch.open_signal[list].connect(self.on_startup_args)
  225. self.new_launch.moveToThread(self.th)
  226. self.new_launch.start.emit()
  227. # ############################################################################################################
  228. # # ######################################## OS-specific #####################################################
  229. # ############################################################################################################
  230. portable = False
  231. # Folder for user settings.
  232. if sys.platform == 'win32':
  233. if platform.architecture()[0] == '32bit':
  234. App.log.debug("Win32!")
  235. else:
  236. App.log.debug("Win64!")
  237. # #######################################################################################################
  238. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  239. # #######################################################################################################
  240. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  241. try:
  242. with open(config_file, 'r'):
  243. pass
  244. except FileNotFoundError:
  245. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  246. try:
  247. with open(config_file, 'r') as f:
  248. try:
  249. for line in f:
  250. param = str(line).replace('\n', '').rpartition('=')
  251. if param[0] == 'portable':
  252. try:
  253. portable = eval(param[2])
  254. except NameError:
  255. portable = False
  256. if param[0] == 'headless':
  257. if param[2].lower() == 'true':
  258. self.cmd_line_headless = 1
  259. else:
  260. self.cmd_line_headless = None
  261. except Exception as e:
  262. log.debug('App.__init__() -->%s' % str(e))
  263. return
  264. except FileNotFoundError as e:
  265. log.debug(str(e))
  266. pass
  267. if portable is False:
  268. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  269. else:
  270. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  271. self.os = 'windows'
  272. else: # Linux/Unix/MacOS
  273. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  274. self.os = 'unix'
  275. # ############################################################################################################
  276. # ################################# Setup folders and files ##################################################
  277. # ############################################################################################################
  278. if not os.path.exists(self.data_path):
  279. os.makedirs(self.data_path)
  280. App.log.debug('Created data folder: ' + self.data_path)
  281. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  282. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  283. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  284. if not os.path.exists(self.preprocessorpaths):
  285. os.makedirs(self.preprocessorpaths)
  286. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  287. # create geo_tools_db.FlatDB file if there is none
  288. try:
  289. f = open(self.data_path + '/geo_tools_db.FlatDB')
  290. f.close()
  291. except IOError:
  292. App.log.debug('Creating empty geo_tool_db.FlatDB')
  293. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  294. json.dump({}, f)
  295. f.close()
  296. # create current_defaults.FlatConfig file if there is none
  297. try:
  298. f = open(self.data_path + '/current_defaults.FlatConfig')
  299. f.close()
  300. except IOError:
  301. App.log.debug('Creating empty current_defaults.FlatConfig')
  302. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  303. json.dump({}, f)
  304. f.close()
  305. # Write factory_defaults.FlatConfig file to disk
  306. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  307. # create a recent files json file if there is none
  308. try:
  309. f = open(self.data_path + '/recent.json')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty recent.json')
  313. f = open(self.data_path + '/recent.json', 'w')
  314. json.dump([], f)
  315. f.close()
  316. # create a recent projects json file if there is none
  317. try:
  318. fp = open(self.data_path + '/recent_projects.json')
  319. fp.close()
  320. except IOError:
  321. App.log.debug('Creating empty recent_projects.json')
  322. fp = open(self.data_path + '/recent_projects.json', 'w')
  323. json.dump([], fp)
  324. fp.close()
  325. # Application directory. CHDIR to it. Otherwise, trying to load
  326. # GUI icons will fail as their path is relative.
  327. # This will fail under cx_freeze ...
  328. self.app_home = os.path.dirname(os.path.realpath(__file__))
  329. App.log.debug("Application path is " + self.app_home)
  330. App.log.debug("Started in " + os.getcwd())
  331. # cx_freeze workaround
  332. if os.path.isfile(self.app_home):
  333. self.app_home = os.path.dirname(self.app_home)
  334. os.chdir(self.app_home)
  335. # ############################################################################################################
  336. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  337. # ############################################################################################################
  338. self.defaults = FlatCAMDefaults()
  339. self.defaults["root_folder_path"] = self.app_home
  340. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  341. if user_defaults:
  342. self.defaults.load(filename=current_defaults_path)
  343. if self.defaults['units'] == 'MM':
  344. self.decimals = int(self.defaults['decimals_metric'])
  345. else:
  346. self.decimals = int(self.defaults['decimals_inch'])
  347. if self.defaults["global_gray_icons"] is False:
  348. self.resource_location = 'assets/resources'
  349. else:
  350. self.resource_location = 'assets/resources/dark_resources'
  351. self.current_units = self.defaults['units']
  352. # ###########################################################################################################
  353. # #################################### SETUP OBJECT CLASSES #################################################
  354. # ###########################################################################################################
  355. self.setup_obj_classes()
  356. # ###########################################################################################################
  357. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  358. # ###########################################################################################################
  359. self.pool = Pool()
  360. # ###########################################################################################################
  361. # ###################################### Setting the Splash Screen ##########################################
  362. # ###########################################################################################################
  363. splash_settings = QSettings("Open Source", "FlatCAM")
  364. if splash_settings.contains("splash_screen"):
  365. show_splash = splash_settings.value("splash_screen")
  366. else:
  367. splash_settings.setValue('splash_screen', 1)
  368. # This will write the setting to the platform specific storage.
  369. del splash_settings
  370. show_splash = 1
  371. if show_splash and self.cmd_line_headless != 1:
  372. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  373. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  374. # self.splash.setMask(splash_pix.mask())
  375. # move splashscreen to the current monitor
  376. desktop = QtWidgets.QApplication.desktop()
  377. screen = desktop.screenNumber(QtGui.QCursor.pos())
  378. current_screen_center = desktop.availableGeometry(screen).center()
  379. self.splash.move(current_screen_center - self.splash.rect().center())
  380. self.splash.show()
  381. self.splash.showMessage(_("FlatCAM is initializing ..."),
  382. alignment=Qt.AlignBottom | Qt.AlignLeft,
  383. color=QtGui.QColor("gray"))
  384. else:
  385. show_splash = 0
  386. # ###########################################################################################################
  387. # ######################################### Initialize GUI ##################################################
  388. # ###########################################################################################################
  389. # FlatCAM colors used in plotting
  390. self.FC_light_green = '#BBF268BF'
  391. self.FC_dark_green = '#006E20BF'
  392. self.FC_light_blue = '#a5a5ffbf'
  393. self.FC_dark_blue = '#0000ffbf'
  394. self.ui = MainGUI(self)
  395. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  396. if theme_settings.contains("theme"):
  397. theme = theme_settings.value('theme', type=str)
  398. else:
  399. theme = 'white'
  400. if self.defaults["global_cursor_color_enabled"]:
  401. self.cursor_color_3D = self.defaults["global_cursor_color"]
  402. else:
  403. if theme == 'white':
  404. self.cursor_color_3D = 'black'
  405. else:
  406. self.cursor_color_3D = 'gray'
  407. # update the defaults dict with the setting in QSetting
  408. self.defaults['global_theme'] = theme
  409. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  410. self.ui.final_save.connect(self.final_save)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform.connect(self.info)
  606. # signal to be called when the app is quiting
  607. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  608. self.message.connect(lambda: message_dialog(parent=self.ui))
  609. # self.progress.connect(self.set_progress_bar)
  610. # signals emitted when file state change
  611. self.file_opened.connect(self.register_recent)
  612. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  613. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  614. # ########################################## Standard signals ###############################################
  615. # ### Menu
  616. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  617. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  618. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  619. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  620. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  621. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  622. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  623. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  624. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  625. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  626. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  627. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  628. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  629. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  630. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  631. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  632. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  633. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  634. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  635. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  636. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  637. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  638. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  639. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  640. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  641. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  642. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  643. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  644. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  645. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  646. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  647. self.ui.menufile_exit.triggered.connect(self.final_save)
  648. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  649. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  650. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  651. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  652. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  653. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  654. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  655. self.ui.menueditdelete.triggered.connect(self.on_delete)
  656. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  657. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  658. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  659. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  660. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  661. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  662. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  663. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  664. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  665. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  666. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  667. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  668. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  669. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  670. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  671. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  672. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  673. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  674. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  675. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  676. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  677. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  678. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  679. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  680. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  681. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  682. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  683. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  684. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  685. self.ui.menuview_replot.triggered.connect(self.plot_all)
  686. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  687. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  688. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  689. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  690. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  692. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  693. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  696. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  697. self.ui.menuhelp_about.triggered.connect(self.on_about)
  698. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  699. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  700. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  701. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  702. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  703. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  704. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  705. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  706. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  707. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  708. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  709. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  710. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  711. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  712. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  713. # ToolBar signals
  714. self.connect_toolbar_signals()
  715. # Notebook and Plot Tab Area signals
  716. # make the right click on the notebook tab and plot tab area tab raise a menu
  717. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  718. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  719. self.on_tab_setup_context_menu()
  720. # activate initial state
  721. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  722. # Context Menu
  723. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  724. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  725. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  726. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  727. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  728. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  729. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  730. self.ui.clearplot.triggered.connect(self.clear_plots)
  731. self.ui.replot.triggered.connect(self.plot_all)
  732. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  733. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  734. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  735. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  736. self.ui.popmenu_move.triggered.connect(self.obj_move)
  737. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  738. # Project Context Menu -> Color Setting
  739. for act in self.ui.menuprojectcolor.actions():
  740. act.triggered.connect(self.on_set_color_action_triggered)
  741. # ###########################################################################################################
  742. # #################################### GUI PREFERENCES SIGNALS ##############################################
  743. # ###########################################################################################################
  744. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  745. lambda: self.on_toggle_units(no_pref=False))
  746. # ##################################### Workspace Setting Signals ###########################################
  747. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  748. self.on_workspace_modified)
  749. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  750. self.on_workspace_modified
  751. )
  752. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  753. # ###########################################################################################################
  754. # ######################################## GUI SETTINGS SIGNALS #############################################
  755. # ###########################################################################################################
  756. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  757. # ######################################## Tools related signals ############################################
  758. # Film Tool
  759. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  760. self.on_film_color_entry)
  761. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  762. self.on_film_color_button)
  763. # QRCode Tool
  764. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  765. self.on_qrcode_fill_color_entry)
  766. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  767. self.on_qrcode_fill_color_button)
  768. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  769. self.on_qrcode_back_color_entry)
  770. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  771. self.on_qrcode_back_color_button)
  772. # portability changed signal
  773. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  774. # Object list
  775. self.object_status_changed.connect(self.collection.on_collection_updated)
  776. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  777. # Export Excellon parameters.
  778. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  779. self.on_update_exc_export
  780. )
  781. # call it once to make sure it is updated at startup
  782. self.on_update_exc_export(state=self.defaults["excellon_update"])
  783. # when there are arguments at application startup this get launched
  784. self.args_at_startup[list].connect(self.on_startup_args)
  785. # ###########################################################################################################
  786. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  787. # ###########################################################################################################
  788. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  789. lambda: self.restore_extensions(ext_type='excellon'))
  790. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  791. lambda: self.restore_extensions(ext_type='gcode'))
  792. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='gerber'))
  794. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  795. lambda: self.delete_all_extensions(ext_type='excellon'))
  796. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  797. lambda: self.delete_all_extensions(ext_type='gcode'))
  798. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='gerber'))
  800. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  801. lambda: self.add_extension(ext_type='excellon'))
  802. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  803. lambda: self.add_extension(ext_type='gcode'))
  804. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='gerber'))
  806. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  807. lambda: self.del_extension(ext_type='excellon'))
  808. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  809. lambda: self.del_extension(ext_type='gcode'))
  810. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='gerber'))
  812. # connect the 'Apply' buttons from the Preferences/File Associations
  813. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  814. lambda: self.on_register_files(obj_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  816. lambda: self.on_register_files(obj_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='gerber'))
  819. # ###########################################################################################################
  820. # ########################################### KEYWORDS SIGNALS ##############################################
  821. # ###########################################################################################################
  822. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  823. lambda: self.restore_extensions(ext_type='keyword'))
  824. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  825. lambda: self.delete_all_extensions(ext_type='keyword'))
  826. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  827. lambda: self.add_extension(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  829. lambda: self.del_extension(ext_type='keyword'))
  830. # connect the abort_all_tasks related slots to the related signals
  831. self.proc_container.idle_flag.connect(self.app_is_idle)
  832. # signal emitted when a tab is closed in the Plot Area
  833. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  834. # signal to close the application
  835. self.close_app_signal.connect(self.kill_app)
  836. # ################################# FINISHED CONNECTING SIGNALS #############################################
  837. # ###########################################################################################################
  838. # ###########################################################################################################
  839. # ###########################################################################################################
  840. self.log.debug("Finished connecting Signals.")
  841. # ###########################################################################################################
  842. # ########################################## Other setups ###################################################
  843. # ###########################################################################################################
  844. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  845. # depending on from where those tools are called different actions can be done
  846. self.call_source = 'app'
  847. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  848. self.tool_tab_locked = False
  849. # decide if to show or hide the Notebook side of the screen at startup
  850. if self.defaults["global_project_at_startup"] is True:
  851. self.ui.splitter.setSizes([1, 1])
  852. else:
  853. self.ui.splitter.setSizes([0, 1])
  854. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  855. self.setup_component_editor()
  856. # ###########################################################################################################
  857. # ####################################### Auto-complete KEYWORDS ############################################
  858. # ###########################################################################################################
  859. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  860. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  861. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  862. 'export_exc',
  863. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  864. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  865. 'interiors', 'isolate', 'join_excellon',
  866. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  867. 'mirror', 'ncc',
  868. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  869. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  870. 'options', 'origin',
  871. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  872. 'save', 'save_project',
  873. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  874. 'skew', 'subtract_poly', 'subtract_rectangle',
  875. 'version', 'write_gcode'
  876. ]
  877. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  878. 'Paste_1',
  879. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  880. 'Toolchange_manual', 'True', 'Users',
  881. 'all', 'auto', 'axis',
  882. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  883. 'contour', 'default',
  884. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  885. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  886. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  887. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  888. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  889. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  890. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  891. 'spacing_columns',
  892. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  893. 'toolchange_xy', 'toolchangez', 'travelz',
  894. 'tooldia', 'use_threads', 'value',
  895. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  896. ]
  897. self.tcl_keywords = [
  898. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  899. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  900. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  901. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  902. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  903. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  904. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  905. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  906. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  907. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  908. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  909. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  910. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  911. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  912. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  913. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  914. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  915. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  916. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  917. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  918. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  919. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  920. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  921. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  922. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  923. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  924. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  925. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  926. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  927. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  928. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  929. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  930. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  931. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  932. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  933. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  934. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  935. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  936. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  937. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  938. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  939. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  940. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  941. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  942. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  943. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  944. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  945. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  946. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  947. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  948. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  949. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  950. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  951. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  952. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  953. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  954. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  955. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  956. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  957. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  958. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  959. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  960. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  961. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  962. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  963. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  964. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  965. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  966. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  967. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  968. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  969. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  970. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  971. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  972. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  973. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  974. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  975. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  976. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  977. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  978. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  979. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  980. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  981. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  982. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  983. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  984. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  985. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  986. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  987. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  988. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  989. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  990. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  991. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  992. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  993. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  994. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  995. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  996. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  997. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  998. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  999. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1000. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1001. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1002. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1003. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1004. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1005. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1006. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1007. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1008. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1009. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1010. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1011. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1012. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1013. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1014. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1015. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1016. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1017. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1018. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1019. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1020. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1021. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1022. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1023. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1024. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1025. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1026. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1027. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1028. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1029. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1030. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1031. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1032. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1033. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1034. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1035. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1036. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1037. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1038. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1039. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1040. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1041. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1042. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1043. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1044. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1045. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1046. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1047. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1048. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1049. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1050. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1051. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1052. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1053. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1054. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1055. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1056. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1057. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1058. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1059. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1060. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1061. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1062. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1063. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1064. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1065. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1066. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1067. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1068. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1069. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1070. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1071. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1072. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1073. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1074. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1075. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1076. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1077. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1078. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1079. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1080. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1081. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1082. ]
  1083. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1084. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1085. # ###########################################################################################################
  1086. # ############################################## Shell SETUP ################################################
  1087. # ###########################################################################################################
  1088. self.shell = FCShell(app=self, version=self.version)
  1089. self.ui.shell_dock.setWidget(self.shell)
  1090. self.log.debug("TCL Shell has been initialized.")
  1091. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1092. if self.defaults["global_shell_at_startup"]:
  1093. self.ui.shell_dock.show()
  1094. else:
  1095. self.ui.shell_dock.hide()
  1096. # ###########################################################################################################
  1097. # ########################################## Tools and Plugins ##############################################
  1098. # ###########################################################################################################
  1099. self.dblsidedtool = None
  1100. self.distance_tool = None
  1101. self.distance_min_tool = None
  1102. self.panelize_tool = None
  1103. self.film_tool = None
  1104. self.paste_tool = None
  1105. self.calculator_tool = None
  1106. self.rules_tool = None
  1107. self.sub_tool = None
  1108. self.move_tool = None
  1109. self.cutout_tool = None
  1110. self.ncclear_tool = None
  1111. self.optimal_tool = None
  1112. self.paint_tool = None
  1113. self.transform_tool = None
  1114. self.properties_tool = None
  1115. self.pdf_tool = None
  1116. self.image_tool = None
  1117. self.pcb_wizard_tool = None
  1118. self.cal_exc_tool = None
  1119. self.qrcode_tool = None
  1120. self.copper_thieving_tool = None
  1121. self.fiducial_tool = None
  1122. self.edrills_tool = None
  1123. self.align_objects_tool = None
  1124. self.punch_tool = None
  1125. self.invert_tool = None
  1126. self.corners_tool = None
  1127. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1128. try:
  1129. self.install_tools()
  1130. except AttributeError as e:
  1131. log.debug("App.__init__() install tools() --> %s" % str(e))
  1132. # ###########################################################################################################
  1133. # ############################################ SETUP RECENT ITEMS ###########################################
  1134. # ###########################################################################################################
  1135. self.setup_recent_items()
  1136. # ###########################################################################################################
  1137. # ######################################### BookMarks Manager ###############################################
  1138. # ###########################################################################################################
  1139. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1140. self.install_bookmarks()
  1141. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1142. # ###########################################################################################################
  1143. # ########################################### Tools Database ################################################
  1144. # ###########################################################################################################
  1145. self.tools_db_tab = None
  1146. # ### System Font Parsing ###
  1147. # self.f_parse = ParseFont(self)
  1148. # self.parse_system_fonts()
  1149. # ###########################################################################################################
  1150. # ######################################### Check for updates ###############################################
  1151. # ###########################################################################################################
  1152. # Separate thread (Not worker)
  1153. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1154. if (self.beta is False or self.beta is None) and \
  1155. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1156. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1157. # self.thr2 = QtCore.QThread()
  1158. self.worker_task.emit({'fcn': self.version_check,
  1159. 'params': []})
  1160. # self.thr2.start(QtCore.QThread.LowPriority)
  1161. # ###########################################################################################################
  1162. # ##################################### Register files with FlatCAM; #######################################
  1163. # ################################### It works only for Windows for now ####################################
  1164. # ###########################################################################################################
  1165. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1166. self.on_register_files()
  1167. # ###########################################################################################################
  1168. # ######################################## Variables for global usage #######################################
  1169. # ###########################################################################################################
  1170. # hold the App units
  1171. self.units = 'MM'
  1172. # coordinates for relative position display
  1173. self.rel_point1 = (0, 0)
  1174. self.rel_point2 = (0, 0)
  1175. # variable to store coordinates
  1176. self.pos = (0, 0)
  1177. self.pos_canvas = (0, 0)
  1178. self.pos_jump = (0, 0)
  1179. # variable to store mouse coordinates
  1180. self.mouse = [0, 0]
  1181. # variable to store the delta positions on cavnas
  1182. self.dx = 0
  1183. self.dy = 0
  1184. # decide if we have a double click or single click
  1185. self.doubleclick = False
  1186. # store here the is_dragging value
  1187. self.event_is_dragging = False
  1188. # variable to store if a command is active (then the var is not None) and which one it is
  1189. self.command_active = None
  1190. # variable to store the status of moving selection action
  1191. # None value means that it's not an selection action
  1192. # True value = a selection from left to right
  1193. # False value = a selection from right to left
  1194. self.selection_type = None
  1195. # List to store the objects that are currently loaded in FlatCAM
  1196. # This list is updated on each object creation or object delete
  1197. self.all_objects_list = []
  1198. self.objects_under_the_click_list = []
  1199. # List to store the objects that are selected
  1200. self.sel_objects_list = []
  1201. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1202. self.key_modifiers = None
  1203. # Variable to hold the status of the axis
  1204. self.toggle_axis = True
  1205. # Variable to hold the status of the grid lines
  1206. self.toggle_grid_lines = True
  1207. # Variable to store the status of the code editor
  1208. self.toggle_codeeditor = False
  1209. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1210. self.click_noproject = False
  1211. self.cursor = None
  1212. # Variable to store the GCODE that was edited
  1213. self.gcode_edited = ""
  1214. self.text_editor_tab = None
  1215. # reference for the self.ui.code_editor
  1216. self.reference_code_editor = None
  1217. self.script_code = ''
  1218. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1219. self.tools_db_changed_flag = False
  1220. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1221. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1222. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1223. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1224. 'tsm']
  1225. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1226. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1227. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1228. 'sbp', 'tap', 'xpi']
  1229. self.svg_list = ['svg']
  1230. self.dxf_list = ['dxf']
  1231. self.pdf_list = ['pdf']
  1232. self.prj_list = ['flatprj']
  1233. self.conf_list = ['flatconfig']
  1234. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1235. # flag for polygons not cleared
  1236. self.poly_not_cleared = False
  1237. # VisPy visuals
  1238. self.isHovering = False
  1239. self.notHovering = True
  1240. # Window geometry
  1241. self.x_pos = None
  1242. self.y_pos = None
  1243. self.width = None
  1244. self.height = None
  1245. # when True, the app has to return from any thread
  1246. self.abort_flag = False
  1247. # set the value used in the Windows Title
  1248. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1249. # this holds a widget that is installed in the Plot Area when View Source option is used
  1250. self.source_editor_tab = None
  1251. self.pagesize = {}
  1252. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1253. # VisPy visuals
  1254. if self.is_legacy is False:
  1255. try:
  1256. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1257. except AttributeError:
  1258. self.tool_shapes = None
  1259. else:
  1260. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1261. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1262. # used in the delayed shutdown self.start_delayed_quit() method
  1263. self.save_timer = None
  1264. # ###########################################################################################################
  1265. # ################################## ADDING FlatCAM EDITORS section #########################################
  1266. # ###########################################################################################################
  1267. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1268. # at the first launch of the App , the editors will not be functional.
  1269. try:
  1270. self.geo_editor = FlatCAMGeoEditor(self)
  1271. except AttributeError:
  1272. pass
  1273. try:
  1274. self.exc_editor = FlatCAMExcEditor(self)
  1275. except AttributeError:
  1276. pass
  1277. try:
  1278. self.grb_editor = FlatCAMGrbEditor(self)
  1279. except AttributeError:
  1280. pass
  1281. self.log.debug("Finished adding FlatCAM Editor's.")
  1282. self.set_ui_title(name=_("New Project - Not saved"))
  1283. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1284. current_platform = platform.architecture()[0]
  1285. if current_platform != '64bit':
  1286. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1287. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1288. # ###########################################################################################################
  1289. # ########################################### EXCLUSION AREAS ###############################################
  1290. # ###########################################################################################################
  1291. self.exc_areas = ExclusionAreas(app=self)
  1292. # ###########################################################################################################
  1293. # ##################################### Finished the CONSTRUCTOR ############################################
  1294. # ###########################################################################################################
  1295. App.log.debug("END of constructor. Releasing control.")
  1296. # ###########################################################################################################
  1297. # ########################################## SHOW GUI #######################################################
  1298. # ###########################################################################################################
  1299. # if the app is not started as headless, show it
  1300. if self.cmd_line_headless != 1:
  1301. if show_splash:
  1302. # finish the splash
  1303. self.splash.finish(self.ui)
  1304. mgui_settings = QSettings("Open Source", "FlatCAM")
  1305. if mgui_settings.contains("maximized_gui"):
  1306. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1307. if maximized_ui is True:
  1308. self.ui.showMaximized()
  1309. else:
  1310. self.ui.show()
  1311. else:
  1312. self.ui.show()
  1313. if self.defaults["global_systray_icon"]:
  1314. self.trayIcon.show()
  1315. else:
  1316. log.warning("******************* RUNNING HEADLESS *******************")
  1317. # ###########################################################################################################
  1318. # ######################################## START-UP ARGUMENTS ###############################################
  1319. # ###########################################################################################################
  1320. # test if the program was started with a script as parameter
  1321. if self.cmd_line_shellvar:
  1322. try:
  1323. cnt = 0
  1324. command_tcl = 0
  1325. for i in self.cmd_line_shellvar.split(','):
  1326. if i is not None:
  1327. # noinspection PyBroadException
  1328. try:
  1329. command_tcl = eval(i)
  1330. except Exception:
  1331. command_tcl = i
  1332. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1333. cnt += 1
  1334. # if there are Windows paths then replace the path separator with a Unix like one
  1335. if sys.platform == 'win32':
  1336. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1337. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1338. except Exception as ext:
  1339. print("ERROR: ", ext)
  1340. sys.exit(2)
  1341. if self.cmd_line_shellfile:
  1342. if self.cmd_line_headless != 1:
  1343. if self.ui.shell_dock.isHidden():
  1344. self.ui.shell_dock.show()
  1345. try:
  1346. with open(self.cmd_line_shellfile, "r") as myfile:
  1347. # if show_splash:
  1348. # self.splash.showMessage('%s: %ssec\n%s' % (
  1349. # _("Canvas initialization started.\n"
  1350. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1351. # _("Executing Tcl Script ...")),
  1352. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1353. # color=QtGui.QColor("gray"))
  1354. cmd_line_shellfile_text = myfile.read()
  1355. if self.cmd_line_headless != 1:
  1356. self.shell.exec_command(cmd_line_shellfile_text)
  1357. else:
  1358. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1359. except Exception as ext:
  1360. print("ERROR: ", ext)
  1361. sys.exit(2)
  1362. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1363. # the path/file_name must be enclosed in quotes if it contain spaces
  1364. if App.args:
  1365. self.args_at_startup.emit(App.args)
  1366. if self.defaults.old_defaults_found is True:
  1367. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1368. "Please reboot the application to update."))
  1369. self.defaults.old_defaults_found = False
  1370. # ######################################### INIT FINISHED #######################################################
  1371. # #################################################################################################################
  1372. # #################################################################################################################
  1373. # #################################################################################################################
  1374. # #################################################################################################################
  1375. # #################################################################################################################
  1376. @staticmethod
  1377. def copy_and_overwrite(from_path, to_path):
  1378. """
  1379. From here:
  1380. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1381. :param from_path: source path
  1382. :param to_path: destination path
  1383. :return: None
  1384. """
  1385. if os.path.exists(to_path):
  1386. shutil.rmtree(to_path)
  1387. try:
  1388. shutil.copytree(from_path, to_path)
  1389. except FileNotFoundError:
  1390. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1391. shutil.copytree(from_new_path, to_path)
  1392. def on_startup_args(self, args, silent=False):
  1393. """
  1394. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1395. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1396. :param args: a list containing the application args at startup
  1397. :return: None
  1398. """
  1399. if args is not None:
  1400. args_to_process = args
  1401. else:
  1402. args_to_process = App.args
  1403. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1404. for argument in args_to_process:
  1405. if '.FlatPrj'.lower() in argument.lower():
  1406. try:
  1407. project_name = str(argument)
  1408. if project_name == "":
  1409. if silent is False:
  1410. self.inform.emit(_("Cancelled."))
  1411. else:
  1412. # self.open_project(project_name)
  1413. run_from_arg = True
  1414. # self.worker_task.emit({'fcn': self.open_project,
  1415. # 'params': [project_name, run_from_arg]})
  1416. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1417. except Exception as e:
  1418. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1419. elif '.FlatConfig'.lower() in argument.lower():
  1420. try:
  1421. file_name = str(argument)
  1422. if file_name == "":
  1423. if silent is False:
  1424. self.inform.emit(_("Open Config file failed."))
  1425. else:
  1426. run_from_arg = True
  1427. # self.worker_task.emit({'fcn': self.open_config_file,
  1428. # 'params': [file_name, run_from_arg]})
  1429. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1430. except Exception as e:
  1431. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1432. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1433. try:
  1434. file_name = str(argument)
  1435. if file_name == "":
  1436. if silent is False:
  1437. self.inform.emit(_("Open Script file failed."))
  1438. else:
  1439. if silent is False:
  1440. self.on_fileopenscript(name=file_name)
  1441. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1442. self.on_filerunscript(name=file_name)
  1443. except Exception as e:
  1444. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1445. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1446. log.debug("App.on_startup_args() --> Quit event.")
  1447. sys.exit()
  1448. elif 'save'.lower() in argument.lower():
  1449. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1450. self.preferencesUiManager.save_defaults()
  1451. else:
  1452. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1453. proc_arg = argument.lower()
  1454. for ext in exc_list:
  1455. proc_ext = ext.replace(' ', '')
  1456. proc_ext = '.%s' % proc_ext
  1457. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1458. file_name = str(argument)
  1459. if file_name == "":
  1460. if silent is False:
  1461. self.inform.emit(_("Open Excellon file failed."))
  1462. else:
  1463. self.on_fileopenexcellon(name=file_name, signal=None)
  1464. return
  1465. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1466. for ext in gco_list:
  1467. proc_ext = ext.replace(' ', '')
  1468. proc_ext = '.%s' % proc_ext
  1469. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1470. file_name = str(argument)
  1471. if file_name == "":
  1472. if silent is False:
  1473. self.inform.emit(_("Open GCode file failed."))
  1474. else:
  1475. self.on_fileopengcode(name=file_name, signal=None)
  1476. return
  1477. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1478. for ext in grb_list:
  1479. proc_ext = ext.replace(' ', '')
  1480. proc_ext = '.%s' % proc_ext
  1481. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1482. file_name = str(argument)
  1483. if file_name == "":
  1484. if silent is False:
  1485. self.inform.emit(_("Open Gerber file failed."))
  1486. else:
  1487. self.on_fileopengerber(name=file_name, signal=None)
  1488. return
  1489. # if it reached here without already returning then the app was registered with a file that it does not
  1490. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1491. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1492. # for arg in args_to_process:
  1493. # if 'FlatCAM.exe' in arg:
  1494. # continue
  1495. # else:
  1496. # sys.exit(2)
  1497. def set_ui_title(self, name):
  1498. """
  1499. Sets the title of the main window.
  1500. :param name: String that store the project path and project name
  1501. :return: None
  1502. """
  1503. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1504. (self.version,
  1505. ('BETA' if self.beta else ''),
  1506. platform.architecture()[0],
  1507. self.engine,
  1508. name)
  1509. )
  1510. def on_app_restart(self):
  1511. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1512. # be left in the SySTray
  1513. try:
  1514. self.trayIcon.hide()
  1515. except Exception:
  1516. pass
  1517. fcTranslate.restart_program(app=self)
  1518. def clear_pool(self):
  1519. """
  1520. Clear the multiprocessing pool and calls garbage collector.
  1521. :return: None
  1522. """
  1523. self.pool.close()
  1524. self.pool = Pool()
  1525. self.pool_recreated.emit(self.pool)
  1526. gc.collect()
  1527. def install_tools(self):
  1528. """
  1529. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1530. Instantiation of the Tools classes.
  1531. The order that the tools are installed is important as they can depend on each other install position.
  1532. :return: None
  1533. """
  1534. self.distance_tool = Distance(self)
  1535. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1536. before=self.ui.menueditorigin,
  1537. separator=False)
  1538. self.distance_min_tool = DistanceMin(self)
  1539. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1540. pos=self.ui.menuedit,
  1541. before=self.ui.menueditorigin,
  1542. separator=True)
  1543. self.dblsidedtool = DblSidedTool(self)
  1544. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1545. self.cal_exc_tool = ToolCalibration(self)
  1546. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1547. before=self.dblsidedtool.menuAction,
  1548. separator=False)
  1549. self.align_objects_tool = AlignObjects(self)
  1550. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1551. self.edrills_tool = ToolExtractDrills(self)
  1552. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1553. self.panelize_tool = Panelize(self)
  1554. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1555. self.film_tool = Film(self)
  1556. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1557. self.paste_tool = SolderPaste(self)
  1558. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1559. self.calculator_tool = ToolCalculator(self)
  1560. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1561. self.sub_tool = ToolSub(self)
  1562. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1563. pos=self.ui.menutool, separator=True)
  1564. self.rules_tool = RulesCheck(self)
  1565. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1566. pos=self.ui.menutool, separator=False)
  1567. self.optimal_tool = ToolOptimal(self)
  1568. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1569. pos=self.ui.menutool, separator=True)
  1570. self.move_tool = ToolMove(self)
  1571. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1572. before=self.ui.menueditorigin, separator=True)
  1573. self.cutout_tool = CutOut(self)
  1574. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1575. before=self.sub_tool.menuAction)
  1576. self.ncclear_tool = NonCopperClear(self)
  1577. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1578. before=self.sub_tool.menuAction, separator=True)
  1579. self.paint_tool = ToolPaint(self)
  1580. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1581. before=self.sub_tool.menuAction, separator=True)
  1582. self.copper_thieving_tool = ToolCopperThieving(self)
  1583. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1584. pos=self.ui.menutool)
  1585. self.fiducial_tool = ToolFiducials(self)
  1586. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1587. pos=self.ui.menutool)
  1588. self.qrcode_tool = QRCode(self)
  1589. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1590. pos=self.ui.menutool)
  1591. self.punch_tool = ToolPunchGerber(self)
  1592. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1593. self.invert_tool = ToolInvertGerber(self)
  1594. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1595. self.corners_tool = ToolCorners(self)
  1596. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1597. self.transform_tool = ToolTransform(self)
  1598. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1599. pos=self.ui.menuoptions, separator=True)
  1600. self.properties_tool = Properties(self)
  1601. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1602. pos=self.ui.menuoptions)
  1603. self.pdf_tool = ToolPDF(self)
  1604. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1605. pos=self.ui.menufileimport,
  1606. separator=True)
  1607. self.image_tool = ToolImage(self)
  1608. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1609. pos=self.ui.menufileimport,
  1610. separator=True)
  1611. self.pcb_wizard_tool = PcbWizard(self)
  1612. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1613. pos=self.ui.menufileimport)
  1614. self.log.debug("Tools are installed.")
  1615. def remove_tools(self):
  1616. """
  1617. Will remove all the actions in the Tool menu.
  1618. :return: None
  1619. """
  1620. for act in self.ui.menutool.actions():
  1621. self.ui.menutool.removeAction(act)
  1622. def init_tools(self):
  1623. """
  1624. Initialize the Tool tab in the notebook side of the central widget.
  1625. Remove the actions in the Tools menu.
  1626. Instantiate again the FlatCAM tools (plugins).
  1627. All this is required when changing the layout: standard, compact etc.
  1628. :return: None
  1629. """
  1630. log.debug("init_tools()")
  1631. # delete the data currently in the Tools Tab and the Tab itself
  1632. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1633. if widget is not None:
  1634. widget.deleteLater()
  1635. self.ui.notebook.removeTab(2)
  1636. # rebuild the Tools Tab
  1637. self.ui.tool_tab = QtWidgets.QWidget()
  1638. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1639. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1640. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1641. self.ui.tool_scroll_area = VerticalScrollArea()
  1642. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1643. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1644. # first remove all of them
  1645. self.remove_tools()
  1646. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1647. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1648. '&Command Line\tS')
  1649. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1650. # third install all of them
  1651. try:
  1652. self.install_tools()
  1653. except AttributeError:
  1654. pass
  1655. self.log.debug("Tools are initialized.")
  1656. # def parse_system_fonts(self):
  1657. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1658. # 'params': []})
  1659. def connect_toolbar_signals(self):
  1660. """
  1661. Reconnect the signals to the actions in the toolbar.
  1662. This has to be done each time after the FlatCAM tools are removed/installed.
  1663. :return: None
  1664. """
  1665. # Toolbar
  1666. # File Toolbar Signals
  1667. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1668. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1669. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1670. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1671. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1672. # View Toolbar Signals
  1673. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1674. self.ui.replot_btn.triggered.connect(self.plot_all)
  1675. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1676. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1677. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1678. # Edit Toolbar Signals
  1679. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1680. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1681. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1682. self.ui.delete_btn.triggered.connect(self.on_delete)
  1683. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1684. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1685. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1686. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1687. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1688. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1689. # Scripting Toolbar Signals
  1690. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1691. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1692. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1693. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1694. # Tools Toolbar Signals
  1695. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1696. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1697. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1698. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1699. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1700. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1701. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1702. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1703. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1704. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1705. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1706. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1707. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1708. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1709. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1710. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1711. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1712. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1713. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1714. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1715. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1716. def object2editor(self):
  1717. """
  1718. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1719. :return: None
  1720. """
  1721. self.defaults.report_usage("object2editor()")
  1722. # disable the objects menu as it may interfere with the AppEditors
  1723. self.ui.menuobjects.setDisabled(True)
  1724. edited_object = self.collection.get_active()
  1725. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1726. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1727. pass
  1728. else:
  1729. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1730. return
  1731. if isinstance(edited_object, GeometryObject):
  1732. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1733. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1734. # we set the notebook to hidden
  1735. # self.ui.splitter.setSizes([0, 1])
  1736. if edited_object.multigeo is True:
  1737. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1738. if len(sel_rows) > 1:
  1739. self.inform.emit('[WARNING_NOTCL] %s' %
  1740. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1741. "is not possible.\n"
  1742. "Edit only one geometry at a time."))
  1743. # determine the tool dia of the selected tool
  1744. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1745. # now find the key in the edited_object.tools that has this tooldia
  1746. multi_tool = 1
  1747. for tool in edited_object.tools:
  1748. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1749. multi_tool = tool
  1750. break
  1751. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1752. else:
  1753. self.geo_editor.edit_fcgeometry(edited_object)
  1754. # set call source to the Editor we go into
  1755. self.call_source = 'geo_editor'
  1756. elif isinstance(edited_object, ExcellonObject):
  1757. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1758. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1759. if self.ui.splitter.sizes()[0] == 0:
  1760. self.ui.splitter.setSizes([1, 1])
  1761. self.exc_editor.edit_fcexcellon(edited_object)
  1762. # set call source to the Editor we go into
  1763. self.call_source = 'exc_editor'
  1764. elif isinstance(edited_object, GerberObject):
  1765. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1766. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1767. if self.ui.splitter.sizes()[0] == 0:
  1768. self.ui.splitter.setSizes([1, 1])
  1769. self.grb_editor.edit_fcgerber(edited_object)
  1770. # set call source to the Editor we go into
  1771. self.call_source = 'grb_editor'
  1772. # reset the following variables so the UI is built again after edit
  1773. edited_object.ui_build = False
  1774. edited_object.build_aperture_storage = False
  1775. elif isinstance(edited_object, CNCJobObject):
  1776. if self.ui.splitter.sizes()[0] == 0:
  1777. self.ui.splitter.setSizes([1, 1])
  1778. edited_object.on_edit_code_click()
  1779. return
  1780. # make sure that we can't select another object while in Editor Mode:
  1781. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1782. self.ui.project_frame.setDisabled(True)
  1783. # delete any selection shape that might be active as they are not relevant in Editor
  1784. self.delete_selection_shape()
  1785. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1786. self.ui.plot_tab_area.protectTab(0)
  1787. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1788. self.should_we_save = True
  1789. def editor2object(self, cleanup=None):
  1790. """
  1791. Transfers the Geometry or Excellon from it's editor to the current object.
  1792. :return: None
  1793. """
  1794. self.defaults.report_usage("editor2object()")
  1795. # re-enable the objects menu that was disabled on entry in Editor mode
  1796. self.ui.menuobjects.setDisabled(False)
  1797. # do not update a geometry or excellon object unless it comes out of an editor
  1798. if self.call_source != 'app':
  1799. edited_obj = self.collection.get_active()
  1800. if cleanup is None:
  1801. msgbox = QtWidgets.QMessageBox()
  1802. msgbox.setText(_("Do you want to save the edited object?"))
  1803. msgbox.setWindowTitle(_("Close Editor"))
  1804. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1805. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1806. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1807. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1808. msgbox.setDefaultButton(bt_yes)
  1809. msgbox.exec_()
  1810. response = msgbox.clickedButton()
  1811. if response == bt_yes:
  1812. # clean the Tools Tab
  1813. self.ui.tool_scroll_area.takeWidget()
  1814. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1815. self.ui.notebook.setTabText(2, "Tool")
  1816. if isinstance(edited_obj, GeometryObject):
  1817. obj_type = "Geometry"
  1818. if cleanup is None:
  1819. self.geo_editor.update_fcgeometry(edited_obj)
  1820. # self.geo_editor.update_options(edited_obj)
  1821. self.geo_editor.deactivate()
  1822. # restore GUI to the Selected TAB
  1823. # Remove anything else in the AppGUI
  1824. self.ui.tool_scroll_area.takeWidget()
  1825. # update the geo object options so it is including the bounding box values
  1826. try:
  1827. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1828. edited_obj.options['xmin'] = xmin
  1829. edited_obj.options['ymin'] = ymin
  1830. edited_obj.options['xmax'] = xmax
  1831. edited_obj.options['ymax'] = ymax
  1832. except AttributeError as e:
  1833. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1834. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1835. edited_obj.build_ui()
  1836. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1837. elif isinstance(edited_obj, GerberObject):
  1838. obj_type = "Gerber"
  1839. if cleanup is None:
  1840. self.grb_editor.update_fcgerber()
  1841. self.grb_editor.update_options(edited_obj)
  1842. self.grb_editor.deactivate_grb_editor()
  1843. # delete the old object (the source object) if it was an empty one
  1844. try:
  1845. if len(edited_obj.solid_geometry) == 0:
  1846. old_name = edited_obj.options['name']
  1847. self.collection.set_active(old_name)
  1848. self.collection.delete_active()
  1849. except TypeError:
  1850. # if the solid_geometry is a single Polygon the len() will not work
  1851. # in any case, falling here means that we have something in the solid_geometry, even if only
  1852. # a single Polygon, therefore we pass this
  1853. pass
  1854. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1855. # restore GUI to the Selected TAB
  1856. # Remove anything else in the AppGUI
  1857. self.ui.selected_scroll_area.takeWidget()
  1858. elif isinstance(edited_obj, ExcellonObject):
  1859. obj_type = "Excellon"
  1860. if cleanup is None:
  1861. self.exc_editor.update_fcexcellon(edited_obj)
  1862. # self.exc_editor.update_options(edited_obj)
  1863. self.exc_editor.deactivate()
  1864. # restore GUI to the Selected TAB
  1865. # Remove anything else in the AppGUI
  1866. self.ui.tool_scroll_area.takeWidget()
  1867. # delete the old object (the source object) if it was an empty one
  1868. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1869. old_name = edited_obj.options['name']
  1870. self.collection.delete_by_name(name=old_name)
  1871. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1872. else:
  1873. self.inform.emit('[WARNING_NOTCL] %s' %
  1874. _("Select a Gerber, Geometry or Excellon Object to update."))
  1875. return
  1876. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1877. elif response == bt_no:
  1878. # clean the Tools Tab
  1879. self.ui.tool_scroll_area.takeWidget()
  1880. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1881. self.ui.notebook.setTabText(2, "Tool")
  1882. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1883. if isinstance(edited_obj, GeometryObject):
  1884. self.geo_editor.deactivate()
  1885. edited_obj.build_ui()
  1886. elif isinstance(edited_obj, GerberObject):
  1887. self.grb_editor.deactivate_grb_editor()
  1888. edited_obj.build_ui()
  1889. elif isinstance(edited_obj, ExcellonObject):
  1890. self.exc_editor.deactivate()
  1891. edited_obj.build_ui()
  1892. else:
  1893. self.inform.emit('[WARNING_NOTCL] %s' %
  1894. _("Select a Gerber, Geometry or Excellon Object to update."))
  1895. return
  1896. elif response == bt_cancel:
  1897. return
  1898. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1899. # edited_obj.build_ui()
  1900. # Switch notebook to Selected page
  1901. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1902. else:
  1903. if isinstance(edited_obj, GeometryObject):
  1904. self.geo_editor.deactivate()
  1905. elif isinstance(edited_obj, GerberObject):
  1906. self.grb_editor.deactivate_grb_editor()
  1907. elif isinstance(edited_obj, ExcellonObject):
  1908. self.exc_editor.deactivate()
  1909. else:
  1910. self.inform.emit('[WARNING_NOTCL] %s' %
  1911. _("Select a Gerber, Geometry or Excellon Object to update."))
  1912. return
  1913. # if notebook is hidden we show it
  1914. if self.ui.splitter.sizes()[0] == 0:
  1915. self.ui.splitter.setSizes([1, 1])
  1916. # restore the call_source to app
  1917. self.call_source = 'app'
  1918. edited_obj.plot()
  1919. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1920. self.ui.plot_tab_area.protectTab(0)
  1921. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1922. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1923. self.ui.project_frame.setDisabled(False)
  1924. def get_last_folder(self):
  1925. """
  1926. Get the folder path from where the last file was opened.
  1927. :return: String, last opened folder path
  1928. """
  1929. return self.defaults["global_last_folder"]
  1930. def get_last_save_folder(self):
  1931. """
  1932. Get the folder path from where the last file was saved.
  1933. :return: String, last saved folder path
  1934. """
  1935. loc = self.defaults["global_last_save_folder"]
  1936. if loc is None:
  1937. loc = self.defaults["global_last_folder"]
  1938. if loc is None:
  1939. loc = os.path.dirname(__file__)
  1940. return loc
  1941. def info(self, msg):
  1942. """
  1943. Informs the user. Normally on the status bar, optionally
  1944. also on the shell.
  1945. :param msg: Text to write.
  1946. :return: None
  1947. """
  1948. # Type of message in brackets at the beginning of the message.
  1949. match = re.search(r"\[(.*)\](.*)", msg)
  1950. if match:
  1951. level = match.group(1)
  1952. msg_ = match.group(2)
  1953. self.ui.fcinfo.set_status(str(msg_), level=level)
  1954. if level.lower() == "error":
  1955. self.shell_message(msg, error=True, show=True)
  1956. elif level.lower() == "warning":
  1957. self.shell_message(msg, warning=True, show=True)
  1958. elif level.lower() == "error_notcl":
  1959. self.shell_message(msg, error=True, show=False)
  1960. elif level.lower() == "warning_notcl":
  1961. self.shell_message(msg, warning=True, show=False)
  1962. elif level.lower() == "success":
  1963. self.shell_message(msg, success=True, show=False)
  1964. elif level.lower() == "selected":
  1965. self.shell_message(msg, selected=True, show=False)
  1966. else:
  1967. self.shell_message(msg, show=False)
  1968. else:
  1969. self.ui.fcinfo.set_status(str(msg), level="info")
  1970. # make sure that if the message is to clear the infobar with a space
  1971. # is not printed over and over on the shell
  1972. if msg != '':
  1973. self.shell_message(msg)
  1974. def on_import_preferences(self):
  1975. """
  1976. Loads the application default settings from a saved file into
  1977. ``self.defaults`` dictionary.
  1978. :return: None
  1979. """
  1980. self.defaults.report_usage("on_import_preferences")
  1981. App.log.debug("App.on_import_preferences()")
  1982. # Show file chooser
  1983. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1984. try:
  1985. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1986. directory=self.data_path,
  1987. filter=filter_)
  1988. except TypeError:
  1989. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1990. filter=filter_)
  1991. filename = str(filename)
  1992. if filename == "":
  1993. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1994. return
  1995. # Load in the defaults from the chosen file
  1996. self.defaults.load(filename=filename)
  1997. self.preferencesUiManager.on_preferences_edited()
  1998. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1999. def on_export_preferences(self):
  2000. """
  2001. Save the defaults dictionary to a file.
  2002. :return: None
  2003. """
  2004. self.defaults.report_usage("on_export_preferences")
  2005. App.log.debug("on_export_preferences()")
  2006. # defaults_file_content = None
  2007. # Show file chooser
  2008. date = str(datetime.today()).rpartition('.')[0]
  2009. date = ''.join(c for c in date if c not in ':-')
  2010. date = date.replace(' ', '_')
  2011. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2012. try:
  2013. filename, _f = FCFileSaveDialog.get_saved_filename(
  2014. caption=_("Export FlatCAM Preferences"),
  2015. directory=self.data_path + '/preferences_' + date,
  2016. filter=filter__
  2017. )
  2018. except TypeError:
  2019. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2020. filename = str(filename)
  2021. if filename == "":
  2022. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2023. return
  2024. # Update options
  2025. self.preferencesUiManager.defaults_read_form()
  2026. self.defaults.propagate_defaults()
  2027. # Save update options
  2028. try:
  2029. self.defaults.write(filename=filename)
  2030. except Exception:
  2031. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2032. return
  2033. if self.defaults["global_open_style"] is False:
  2034. self.file_opened.emit("preferences", filename)
  2035. self.file_saved.emit("preferences", filename)
  2036. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2037. def save_to_file(self, content_to_save, txt_content):
  2038. """
  2039. Save something to a file.
  2040. :return: None
  2041. """
  2042. self.defaults.report_usage("save_to_file")
  2043. App.log.debug("save_to_file()")
  2044. self.date = str(datetime.today()).rpartition('.')[0]
  2045. self.date = ''.join(c for c in self.date if c not in ':-')
  2046. self.date = self.date.replace(' ', '_')
  2047. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2048. path_to_save = self.defaults["global_last_save_folder"] if \
  2049. self.defaults["global_last_save_folder"] is not None else self.data_path
  2050. try:
  2051. filename, _f = FCFileSaveDialog.get_saved_filename(
  2052. caption=_("Save to file"),
  2053. directory=path_to_save + '/file_' + self.date,
  2054. filter=filter__
  2055. )
  2056. except TypeError:
  2057. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2058. filename = str(filename)
  2059. if filename == "":
  2060. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2061. return
  2062. else:
  2063. try:
  2064. with open(filename, 'w') as f:
  2065. ___ = f.read()
  2066. except PermissionError:
  2067. self.inform.emit('[WARNING] %s' %
  2068. _("Permission denied, saving not possible.\n"
  2069. "Most likely another app is holding the file open and not accessible."))
  2070. return
  2071. except IOError:
  2072. App.log.debug('Creating a new file ...')
  2073. f = open(filename, 'w')
  2074. f.close()
  2075. except Exception:
  2076. e = sys.exc_info()[0]
  2077. App.log.error("Could not load the file.")
  2078. App.log.error(str(e))
  2079. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2080. return
  2081. # Save content
  2082. if filename.rpartition('.')[2].lower() == 'html':
  2083. file_content = content_to_save
  2084. else:
  2085. file_content = txt_content
  2086. try:
  2087. with open(filename, "w") as f:
  2088. f.write(file_content)
  2089. except Exception:
  2090. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2091. return
  2092. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2093. def save_geometry(self, x, y, width, height, notebook_width):
  2094. """
  2095. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2096. launch of the application.
  2097. :param x: X position of the main window
  2098. :param y: Y position of the main window
  2099. :param width: width of the main window
  2100. :param height: height of the main window
  2101. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2102. :return: None
  2103. """
  2104. self.defaults["global_def_win_x"] = x
  2105. self.defaults["global_def_win_y"] = y
  2106. self.defaults["global_def_win_w"] = width
  2107. self.defaults["global_def_win_h"] = height
  2108. self.defaults["global_def_notebook_width"] = notebook_width
  2109. self.preferencesUiManager.save_defaults()
  2110. def register_recent(self, kind, filename):
  2111. """
  2112. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2113. dictionary.
  2114. :param kind: type of file that was opened
  2115. :param filename: the path and file name for the file that was opened
  2116. :return:
  2117. """
  2118. self.log.debug("register_recent()")
  2119. self.log.debug(" %s" % kind)
  2120. self.log.debug(" %s" % filename)
  2121. record = {'kind': str(kind), 'filename': str(filename)}
  2122. if record in self.recent:
  2123. return
  2124. if record in self.recent_projects:
  2125. return
  2126. if record['kind'] == 'project':
  2127. self.recent_projects.insert(0, record)
  2128. else:
  2129. self.recent.insert(0, record)
  2130. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2131. self.recent.pop()
  2132. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2133. self.recent_projects.pop()
  2134. try:
  2135. f = open(self.data_path + '/recent.json', 'w')
  2136. except IOError:
  2137. App.log.error("Failed to open recent items file for writing.")
  2138. self.inform.emit('[ERROR_NOTCL] %s' %
  2139. _('Failed to open recent files file for writing.'))
  2140. return
  2141. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2142. f.close()
  2143. try:
  2144. fp = open(self.data_path + '/recent_projects.json', 'w')
  2145. except IOError:
  2146. App.log.error("Failed to open recent items file for writing.")
  2147. self.inform.emit('[ERROR_NOTCL] %s' %
  2148. _('Failed to open recent projects file for writing.'))
  2149. return
  2150. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2151. fp.close()
  2152. # Re-build the recent items menu
  2153. self.setup_recent_items()
  2154. def on_about(self):
  2155. """
  2156. Displays the "about" dialog found in the Menu --> Help.
  2157. :return: None
  2158. """
  2159. self.defaults.report_usage("on_about")
  2160. version = self.version
  2161. version_date = self.version_date
  2162. beta = self.beta
  2163. class AboutDialog(QtWidgets.QDialog):
  2164. def __init__(self, app, parent=None):
  2165. QtWidgets.QDialog.__init__(self, parent)
  2166. self.app = app
  2167. # Icon and title
  2168. self.setWindowIcon(parent.app_icon)
  2169. self.setWindowTitle(_("About FlatCAM"))
  2170. self.resize(600, 200)
  2171. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2172. # self.setStyleSheet(
  2173. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2174. # "background-attachment: fixed"
  2175. # )
  2176. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2177. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2178. # palette = QtGui.QPalette()
  2179. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2180. # self.setPalette(palette)
  2181. logo = QtWidgets.QLabel()
  2182. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2183. title = QtWidgets.QLabel(
  2184. "<font size=8><B>FlatCAM</B></font><BR>"
  2185. "{title}<BR>"
  2186. "<BR>"
  2187. "<BR>"
  2188. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2189. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2190. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2191. "<B>{issue}</B></a><BR>".format(
  2192. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2193. devel=_("Development"),
  2194. down=_("DOWNLOAD"),
  2195. issue=_("Issue tracker"))
  2196. )
  2197. title.setOpenExternalLinks(True)
  2198. closebtn = QtWidgets.QPushButton(_("Close"))
  2199. tab_widget = QtWidgets.QTabWidget()
  2200. description_label = QtWidgets.QLabel(
  2201. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2202. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2203. version=version,
  2204. beta=('BETA' if beta else ''),
  2205. date=version_date,
  2206. arch=platform.architecture()[0])
  2207. )
  2208. description_label.setOpenExternalLinks(True)
  2209. lic_lbl_header = QtWidgets.QLabel(
  2210. '%s:<br>%s<br>' % (
  2211. _('Licensed under the MIT license'),
  2212. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2213. "http://www.opensource.org/licenses/mit-license.php</a>"
  2214. )
  2215. )
  2216. lic_lbl_header.setOpenExternalLinks(True)
  2217. lic_lbl_body = QtWidgets.QLabel(
  2218. _(
  2219. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2220. 'of this software and associated documentation files (the "Software"), to deal\n'
  2221. 'in the Software without restriction, including without limitation the rights\n'
  2222. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2223. 'copies of the Software, and to permit persons to whom the Software is\n'
  2224. 'furnished to do so, subject to the following conditions:\n\n'
  2225. 'The above copyright notice and this permission notice shall be included in\n'
  2226. 'all copies or substantial portions of the Software.\n\n'
  2227. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2228. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2229. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2230. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2231. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2232. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2233. 'THE SOFTWARE.'
  2234. )
  2235. )
  2236. attributions_label = QtWidgets.QLabel(
  2237. _(
  2238. 'Some of the icons used are from the following sources:<br>'
  2239. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2240. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2241. 'title="Flaticon">www.flaticon.com</a></div>'
  2242. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2243. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2244. )
  2245. )
  2246. attributions_label.setOpenExternalLinks(True)
  2247. # layouts
  2248. layout1 = QtWidgets.QVBoxLayout()
  2249. layout1_1 = QtWidgets.QHBoxLayout()
  2250. layout1_2 = QtWidgets.QHBoxLayout()
  2251. layout2 = QtWidgets.QHBoxLayout()
  2252. layout3 = QtWidgets.QHBoxLayout()
  2253. self.setLayout(layout1)
  2254. layout1.addLayout(layout1_1)
  2255. layout1.addLayout(layout1_2)
  2256. layout1.addLayout(layout2)
  2257. layout1.addLayout(layout3)
  2258. layout1_1.addStretch()
  2259. layout1_1.addWidget(description_label)
  2260. layout1_2.addWidget(tab_widget)
  2261. self.splash_tab = QtWidgets.QWidget()
  2262. self.splash_tab.setObjectName("splash_about")
  2263. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2264. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2265. tab_widget.addTab(self.splash_tab, _("Splash"))
  2266. self.programmmers_tab = QtWidgets.QWidget()
  2267. self.programmmers_tab.setObjectName("programmers_about")
  2268. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2269. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2270. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2271. self.translators_tab = QtWidgets.QWidget()
  2272. self.translators_tab.setObjectName("translators_about")
  2273. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2274. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2275. tab_widget.addTab(self.translators_tab, _("Translators"))
  2276. self.license_tab = QtWidgets.QWidget()
  2277. self.license_tab.setObjectName("license_about")
  2278. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2279. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2280. tab_widget.addTab(self.license_tab, _("License"))
  2281. self.attributions_tab = QtWidgets.QWidget()
  2282. self.attributions_tab.setObjectName("attributions_about")
  2283. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2284. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2285. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2286. self.splash_tab_layout.addWidget(logo, stretch=0)
  2287. self.splash_tab_layout.addWidget(title, stretch=1)
  2288. pal = QtGui.QPalette()
  2289. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2290. self.prog_grid_lay = QtWidgets.QGridLayout()
  2291. self.prog_grid_lay.setHorizontalSpacing(20)
  2292. self.prog_grid_lay.setColumnStretch(0, 0)
  2293. self.prog_grid_lay.setColumnStretch(2, 1)
  2294. prog_widget = QtWidgets.QWidget()
  2295. prog_widget.setLayout(self.prog_grid_lay)
  2296. prog_scroll = QtWidgets.QScrollArea()
  2297. prog_scroll.setWidget(prog_widget)
  2298. prog_scroll.setWidgetResizable(True)
  2299. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2300. prog_scroll.setPalette(pal)
  2301. self.programmmers_tab_layout.addWidget(prog_scroll)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2349. self.translator_grid_lay = QtWidgets.QGridLayout()
  2350. self.translator_grid_lay.setColumnStretch(0, 0)
  2351. self.translator_grid_lay.setColumnStretch(1, 0)
  2352. self.translator_grid_lay.setColumnStretch(2, 1)
  2353. self.translator_grid_lay.setColumnStretch(3, 0)
  2354. # trans_widget = QtWidgets.QWidget()
  2355. # trans_widget.setLayout(self.translator_grid_lay)
  2356. # self.translators_tab_layout.addWidget(trans_widget)
  2357. # self.translators_tab_layout.addStretch()
  2358. trans_widget = QtWidgets.QWidget()
  2359. trans_widget.setLayout(self.translator_grid_lay)
  2360. trans_scroll = QtWidgets.QScrollArea()
  2361. trans_scroll.setWidget(trans_widget)
  2362. trans_scroll.setWidgetResizable(True)
  2363. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2364. trans_scroll.setPalette(pal)
  2365. self.translators_tab_layout.addWidget(trans_scroll)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2399. self.translator_grid_lay.setColumnStretch(0, 0)
  2400. self.translators_tab_layout.addStretch()
  2401. self.license_tab_layout.addWidget(lic_lbl_header)
  2402. self.license_tab_layout.addWidget(lic_lbl_body)
  2403. self.license_tab_layout.addStretch()
  2404. self.attributions_tab_layout.addWidget(attributions_label)
  2405. self.attributions_tab_layout.addStretch()
  2406. layout3.addStretch()
  2407. layout3.addWidget(closebtn)
  2408. closebtn.clicked.connect(self.accept)
  2409. AboutDialog(app=self, parent=self.ui).exec_()
  2410. def install_bookmarks(self, book_dict=None):
  2411. """
  2412. Install the bookmarks actions in the Help menu -> Bookmarks
  2413. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2414. :return: None
  2415. """
  2416. if book_dict is None:
  2417. self.defaults["global_bookmarks"].update(
  2418. {
  2419. '1': ['FlatCAM', "http://flatcam.org"],
  2420. '2': ['Backup Site', ""]
  2421. }
  2422. )
  2423. else:
  2424. self.defaults["global_bookmarks"].clear()
  2425. self.defaults["global_bookmarks"].update(book_dict)
  2426. # first try to disconnect if somehow they get connected from elsewhere
  2427. for act in self.ui.menuhelp_bookmarks.actions():
  2428. try:
  2429. act.triggered.disconnect()
  2430. except TypeError:
  2431. pass
  2432. # clear all actions except the last one who is the Bookmark manager
  2433. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2434. pass
  2435. else:
  2436. self.ui.menuhelp_bookmarks.removeAction(act)
  2437. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2438. if self.defaults["global_bookmarks"]:
  2439. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2440. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2441. # the JSON is first making the keys as strings (therefore I have to use strings too
  2442. # or do the conversion :(
  2443. # )
  2444. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2445. # the '10' entry jsut after '1' therefore ordering as strings
  2446. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2447. key=lambda x: int(x[0]))
  2448. for entry, bookmark in sorted_bookmarks:
  2449. title = bookmark[0]
  2450. weblink = bookmark[1]
  2451. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2452. act.setText(title)
  2453. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2454. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2455. if title == 'Backup Site' and weblink == "":
  2456. act.triggered.connect(self.on_backup_site)
  2457. else:
  2458. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2459. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2460. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2461. def on_bookmarks_manager(self):
  2462. """
  2463. Adds the bookmark manager in a Tab in Plot Area
  2464. :return:
  2465. """
  2466. for idx in range(self.ui.plot_tab_area.count()):
  2467. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2468. # there can be only one instance of Bookmark Manager at one time
  2469. return
  2470. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2471. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2472. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2473. # add the tab if it was closed
  2474. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2475. # delete the absolute and relative position and messages in the infobar
  2476. self.ui.position_label.setText("")
  2477. # self.ui.rel_position_label.setText("")
  2478. # Switch plot_area to preferences page
  2479. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2480. def on_backup_site(self):
  2481. msgbox = QtWidgets.QMessageBox()
  2482. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2483. "1. FlatCAM.org website is down\n"
  2484. "2. Someone forked FlatCAM project and wants to point\n"
  2485. "to his own website\n\n"
  2486. "If you can't get any informations about FlatCAM beta\n"
  2487. "use the YouTube channel link from the Help menu."))
  2488. msgbox.setWindowTitle(_("Alternative website"))
  2489. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2490. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2491. msgbox.setDefaultButton(bt_yes)
  2492. msgbox.exec_()
  2493. # response = msgbox.clickedButton()
  2494. def on_file_savedefaults(self):
  2495. """
  2496. Callback for menu item File->Save Defaults. Saves application default options
  2497. ``self.defaults`` to current_defaults.FlatConfig.
  2498. :return: None
  2499. """
  2500. self.preferencesUiManager.save_defaults()
  2501. def final_save(self):
  2502. """
  2503. Callback for doing a preferences save to file whenever the application is about to quit.
  2504. If the project has changes, it will ask the user to save the project.
  2505. :return: None
  2506. """
  2507. if self.save_in_progress:
  2508. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2509. return
  2510. if self.should_we_save and self.collection.get_list():
  2511. msgbox = QtWidgets.QMessageBox()
  2512. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2513. "\n"
  2514. "Do you want to Save the project?"))
  2515. msgbox.setWindowTitle(_("Save changes"))
  2516. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2517. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2518. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2519. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2520. msgbox.setDefaultButton(bt_yes)
  2521. msgbox.exec_()
  2522. response = msgbox.clickedButton()
  2523. if response == bt_yes:
  2524. try:
  2525. self.trayIcon.hide()
  2526. except Exception:
  2527. pass
  2528. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2529. elif response == bt_no:
  2530. try:
  2531. self.trayIcon.hide()
  2532. except Exception:
  2533. pass
  2534. self.quit_application()
  2535. elif response == bt_cancel:
  2536. return
  2537. else:
  2538. try:
  2539. self.trayIcon.hide()
  2540. except Exception:
  2541. pass
  2542. self.quit_application()
  2543. def quit_application(self):
  2544. """
  2545. Called (as a pyslot or not) when the application is quit.
  2546. :return: None
  2547. """
  2548. self.preferencesUiManager.save_defaults(silent=True)
  2549. log.debug("App.quit_application() --> App Defaults saved.")
  2550. if self.cmd_line_headless != 1:
  2551. # save app state to file
  2552. stgs = QSettings("Open Source", "FlatCAM")
  2553. stgs.setValue('saved_gui_state', self.ui.saveState())
  2554. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2555. stgs.setValue(
  2556. 'language',
  2557. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2558. )
  2559. stgs.setValue(
  2560. 'notebook_font_size',
  2561. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2562. )
  2563. stgs.setValue(
  2564. 'axis_font_size',
  2565. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2566. )
  2567. stgs.setValue(
  2568. 'textbox_font_size',
  2569. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2570. )
  2571. stgs.setValue(
  2572. 'hud_font_size',
  2573. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2574. )
  2575. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2576. stgs.setValue(
  2577. 'machinist',
  2578. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2579. )
  2580. # This will write the setting to the platform specific storage.
  2581. del stgs
  2582. log.debug("App.quit_application() --> App UI state saved.")
  2583. # try to quit the Socket opened by ArgsThread class
  2584. try:
  2585. self.new_launch.stop.emit()
  2586. except Exception as err:
  2587. log.debug("App.quit_application() --> %s" % str(err))
  2588. # try to quit the QThread that run ArgsThread class
  2589. try:
  2590. self.th.quit()
  2591. except Exception as e:
  2592. log.debug("App.quit_application() --> %s" % str(e))
  2593. # terminate workers
  2594. self.workers.__del__()
  2595. # quit app by signalling for self.kill_app() method
  2596. # self.close_app_signal.emit()
  2597. QtWidgets.qApp.quit()
  2598. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2599. # we use the following command
  2600. minor_v = sys.version_info.minor
  2601. if minor_v < 8:
  2602. sys.exit(0)
  2603. else:
  2604. os._exit(0) # fix to work with Python 3.8
  2605. @staticmethod
  2606. def kill_app():
  2607. QtWidgets.qApp.quit()
  2608. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2609. # we use the following command
  2610. sys.exit(0)
  2611. def on_portable_checked(self, state):
  2612. """
  2613. Callback called when the checkbox in Preferences GUI is checked.
  2614. It will set the application as portable by creating the preferences and recent files in the
  2615. 'config' folder found in the FlatCAM installation folder.
  2616. :param state: boolean, the state of the checkbox when clicked/checked
  2617. :return:
  2618. """
  2619. line_no = 0
  2620. data = None
  2621. if sys.platform != 'win32':
  2622. # this won't work in Linux or MacOS
  2623. return
  2624. # test if the app was frozen and choose the path for the configuration file
  2625. if getattr(sys, "frozen", False) is True:
  2626. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2627. else:
  2628. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2629. config_file = current_data_path + '\\configuration.txt'
  2630. try:
  2631. with open(config_file, 'r') as f:
  2632. try:
  2633. data = f.readlines()
  2634. except Exception as e:
  2635. log.debug('App.__init__() -->%s' % str(e))
  2636. return
  2637. except FileNotFoundError:
  2638. pass
  2639. for line in data:
  2640. line = line.strip('\n')
  2641. param = str(line).rpartition('=')
  2642. if param[0] == 'portable':
  2643. break
  2644. line_no += 1
  2645. if state:
  2646. data[line_no] = 'portable=True\n'
  2647. # create the new defauults files
  2648. # create current_defaults.FlatConfig file if there is none
  2649. try:
  2650. f = open(current_data_path + '/current_defaults.FlatConfig')
  2651. f.close()
  2652. except IOError:
  2653. App.log.debug('Creating empty current_defaults.FlatConfig')
  2654. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2655. json.dump({}, f)
  2656. f.close()
  2657. # create factory_defaults.FlatConfig file if there is none
  2658. try:
  2659. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2660. f.close()
  2661. except IOError:
  2662. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2663. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2664. json.dump({}, f)
  2665. f.close()
  2666. try:
  2667. f = open(current_data_path + '/recent.json')
  2668. f.close()
  2669. except IOError:
  2670. App.log.debug('Creating empty recent.json')
  2671. f = open(current_data_path + '/recent.json', 'w')
  2672. json.dump([], f)
  2673. f.close()
  2674. try:
  2675. fp = open(current_data_path + '/recent_projects.json')
  2676. fp.close()
  2677. except IOError:
  2678. App.log.debug('Creating empty recent_projects.json')
  2679. fp = open(current_data_path + '/recent_projects.json', 'w')
  2680. json.dump([], fp)
  2681. fp.close()
  2682. # save the current defaults to the new defaults file
  2683. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2684. else:
  2685. data[line_no] = 'portable=False\n'
  2686. with open(config_file, 'w') as f:
  2687. f.writelines(data)
  2688. def on_register_files(self, obj_type=None):
  2689. """
  2690. Called whenever there is a need to register file extensions with FlatCAM.
  2691. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2692. :param obj_type: the type of object to be register for.
  2693. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2694. :return: None
  2695. """
  2696. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2697. new_reg_path = 'Software\\Classes\\'
  2698. # find if the current user is admin
  2699. try:
  2700. is_admin = os.getuid() == 0
  2701. except AttributeError:
  2702. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2703. if is_admin is True:
  2704. root_path = winreg.HKEY_LOCAL_MACHINE
  2705. else:
  2706. root_path = winreg.HKEY_CURRENT_USER
  2707. # create the keys
  2708. def set_reg(name, root_pth, new_reg_path, value):
  2709. try:
  2710. winreg.CreateKey(root_pth, new_reg_path)
  2711. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2712. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2713. return True
  2714. except WindowsError:
  2715. return False
  2716. # delete key in registry
  2717. def delete_reg(root_pth, reg_path, key_to_del):
  2718. key_to_del_path = reg_path + key_to_del
  2719. try:
  2720. winreg.DeleteKey(root_pth, key_to_del_path)
  2721. return True
  2722. except WindowsError:
  2723. return False
  2724. if obj_type is None or obj_type == 'excellon':
  2725. exc_list = \
  2726. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2727. exc_list = [x for x in exc_list if x != '']
  2728. # register all keys in the Preferences window
  2729. for ext in exc_list:
  2730. new_k = new_reg_path + '.%s' % ext
  2731. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2732. # and unregister those that are no longer in the Preferences windows but are in the file
  2733. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2734. if ext not in exc_list:
  2735. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2736. # now write the updated extensions to the self.defaults
  2737. # new_ext = ''
  2738. # for ext in exc_list:
  2739. # new_ext = new_ext + ext + ', '
  2740. # self.defaults["fa_excellon"] = new_ext
  2741. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2742. if obj_type is None or obj_type == 'gcode':
  2743. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2744. gco_list = [x for x in gco_list if x != '']
  2745. # register all keys in the Preferences window
  2746. for ext in gco_list:
  2747. new_k = new_reg_path + '.%s' % ext
  2748. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2749. # and unregister those that are no longer in the Preferences windows but are in the file
  2750. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2751. if ext not in gco_list:
  2752. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2753. # now write the updated extensions to the self.defaults
  2754. # new_ext = ''
  2755. # for ext in gco_list:
  2756. # new_ext = new_ext + ext + ', '
  2757. # self.defaults["fa_gcode"] = new_ext
  2758. self.inform.emit('[success] %s' %
  2759. _("Selected GCode file extensions registered with FlatCAM."))
  2760. if obj_type is None or obj_type == 'gerber':
  2761. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2762. grb_list = [x for x in grb_list if x != '']
  2763. # register all keys in the Preferences window
  2764. for ext in grb_list:
  2765. new_k = new_reg_path + '.%s' % ext
  2766. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2767. # and unregister those that are no longer in the Preferences windows but are in the file
  2768. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2769. if ext not in grb_list:
  2770. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2771. # now write the updated extensions to the self.defaults
  2772. # new_ext = ''
  2773. # for ext in grb_list:
  2774. # new_ext = new_ext + ext + ', '
  2775. # self.defaults["fa_gerber"] = new_ext
  2776. self.inform.emit('[success] %s' %
  2777. _("Selected Gerber file extensions registered with FlatCAM."))
  2778. def add_extension(self, ext_type):
  2779. """
  2780. Add a file extension to the list for a specific object
  2781. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2782. :return:
  2783. """
  2784. if ext_type == 'excellon':
  2785. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2786. if new_ext == '':
  2787. return
  2788. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2789. if new_ext in old_val:
  2790. return
  2791. old_val.append(new_ext)
  2792. old_val.sort()
  2793. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2794. if ext_type == 'gcode':
  2795. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2796. if new_ext == '':
  2797. return
  2798. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2799. if new_ext in old_val:
  2800. return
  2801. old_val.append(new_ext)
  2802. old_val.sort()
  2803. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2804. if ext_type == 'gerber':
  2805. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2806. if new_ext == '':
  2807. return
  2808. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2809. if new_ext in old_val:
  2810. return
  2811. old_val.append(new_ext)
  2812. old_val.sort()
  2813. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2814. if ext_type == 'keyword':
  2815. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2816. if new_kw == '':
  2817. return
  2818. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2819. if new_kw in old_val:
  2820. return
  2821. old_val.append(new_kw)
  2822. old_val.sort()
  2823. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2824. # update the self.myKeywords so the model is updated
  2825. self.autocomplete_kw_list = \
  2826. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2827. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2828. self.shell._edit.set_model_data(self.myKeywords)
  2829. def del_extension(self, ext_type):
  2830. """
  2831. Remove a file extension from the list for a specific object
  2832. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2833. :return:
  2834. """
  2835. if ext_type == 'excellon':
  2836. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2837. if new_ext == '':
  2838. return
  2839. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2840. if new_ext not in old_val:
  2841. return
  2842. old_val.remove(new_ext)
  2843. old_val.sort()
  2844. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2845. if ext_type == 'gcode':
  2846. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2847. if new_ext == '':
  2848. return
  2849. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2850. if new_ext not in old_val:
  2851. return
  2852. old_val.remove(new_ext)
  2853. old_val.sort()
  2854. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2855. if ext_type == 'gerber':
  2856. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2857. if new_ext == '':
  2858. return
  2859. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2860. if new_ext not in old_val:
  2861. return
  2862. old_val.remove(new_ext)
  2863. old_val.sort()
  2864. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2865. if ext_type == 'keyword':
  2866. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2867. if new_kw == '':
  2868. return
  2869. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2870. if new_kw not in old_val:
  2871. return
  2872. old_val.remove(new_kw)
  2873. old_val.sort()
  2874. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2875. # update the self.myKeywords so the model is updated
  2876. self.autocomplete_kw_list = \
  2877. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2878. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2879. self.shell._edit.set_model_data(self.myKeywords)
  2880. def restore_extensions(self, ext_type):
  2881. """
  2882. Restore all file extensions associations with FlatCAM, for a specific object
  2883. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2884. :return:
  2885. """
  2886. if ext_type == 'excellon':
  2887. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2888. # for the ability to open Excellon files with .txt extension
  2889. new_exc_list = deepcopy(self.exc_list)
  2890. try:
  2891. new_exc_list.remove('txt')
  2892. except ValueError:
  2893. pass
  2894. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2895. if ext_type == 'gcode':
  2896. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2897. if ext_type == 'gerber':
  2898. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2899. if ext_type == 'keyword':
  2900. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2901. # update the self.myKeywords so the model is updated
  2902. self.autocomplete_kw_list = self.default_keywords
  2903. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2904. self.shell._edit.set_model_data(self.myKeywords)
  2905. def delete_all_extensions(self, ext_type):
  2906. """
  2907. Delete all file extensions associations with FlatCAM, for a specific object
  2908. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2909. :return:
  2910. """
  2911. if ext_type == 'excellon':
  2912. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2913. if ext_type == 'gcode':
  2914. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2915. if ext_type == 'gerber':
  2916. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2917. if ext_type == 'keyword':
  2918. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2919. # update the self.myKeywords so the model is updated
  2920. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2921. self.shell._edit.set_model_data(self.myKeywords)
  2922. def on_edit_join(self, name=None):
  2923. """
  2924. Callback for Edit->Join. Joins the selected geometry objects into
  2925. a new one.
  2926. :return: None
  2927. """
  2928. self.defaults.report_usage("on_edit_join()")
  2929. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2930. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2931. geo_type_set = set()
  2932. objs = self.collection.get_selected()
  2933. if len(objs) < 2:
  2934. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2935. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2936. return 'fail'
  2937. for obj in objs:
  2938. geo_type_set.add(obj.multigeo)
  2939. # if len(geo_type_list) == 1 means that all list elements are the same
  2940. if len(geo_type_set) != 1:
  2941. self.inform.emit('[ERROR] %s' %
  2942. _("Failed join. The Geometry objects are of different types.\n"
  2943. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2944. "convert from one to another and retry joining \n"
  2945. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2946. "the result may not be what was expected. \n"
  2947. "Check the generated GCODE."))
  2948. return
  2949. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2950. if True in geo_type_set:
  2951. def initialize(geo_obj, app):
  2952. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2953. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2954. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2955. for v in geo_obj.tools.values():
  2956. v['data']['name'] = obj_name_multi
  2957. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2958. else:
  2959. def initialize(geo_obj, app):
  2960. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2961. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2962. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2963. for v in geo_obj.tools.values():
  2964. v['data']['name'] = obj_name_single
  2965. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2966. self.should_we_save = True
  2967. def on_edit_join_exc(self):
  2968. """
  2969. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2970. a new Excellon.
  2971. :return: None
  2972. """
  2973. self.defaults.report_usage("on_edit_join_exc()")
  2974. objs = self.collection.get_selected()
  2975. for obj in objs:
  2976. if not isinstance(obj, ExcellonObject):
  2977. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  2978. return
  2979. if len(objs) < 2:
  2980. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2981. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2982. return 'fail'
  2983. def initialize(exc_obj, app):
  2984. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  2985. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  2986. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  2987. self.should_we_save = True
  2988. def on_edit_join_grb(self):
  2989. """
  2990. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2991. a new Gerber object.
  2992. :return: None
  2993. """
  2994. self.defaults.report_usage("on_edit_join_grb()")
  2995. objs = self.collection.get_selected()
  2996. for obj in objs:
  2997. if not isinstance(obj, GerberObject):
  2998. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  2999. return
  3000. if len(objs) < 2:
  3001. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3002. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3003. return 'fail'
  3004. def initialize(grb_obj, app):
  3005. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3006. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3007. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3008. self.should_we_save = True
  3009. def on_convert_singlegeo_to_multigeo(self):
  3010. """
  3011. Called for converting a Geometry object from single-geo to multi-geo.
  3012. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3013. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3014. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3015. the solid-geometry of that tool.
  3016. :return: None
  3017. """
  3018. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3019. obj = self.collection.get_active()
  3020. if obj is None:
  3021. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3022. return
  3023. if not isinstance(obj, GeometryObject):
  3024. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3025. return
  3026. obj.multigeo = True
  3027. for tooluid, dict_value in obj.tools.items():
  3028. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3029. if not isinstance(obj.solid_geometry, list):
  3030. obj.solid_geometry = [obj.solid_geometry]
  3031. # obj.solid_geometry[:] = []
  3032. obj.plot()
  3033. self.should_we_save = True
  3034. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3035. def on_convert_multigeo_to_singlegeo(self):
  3036. """
  3037. Called for converting a Geometry object from multi-geo to single-geo.
  3038. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3039. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3040. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3041. the solid-geometry of that tool.
  3042. :return: None
  3043. """
  3044. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3045. obj = self.collection.get_active()
  3046. if obj is None:
  3047. self.inform.emit('[ERROR_NOTCL] %s' %
  3048. _("Failed. Select a Geometry Object and try again."))
  3049. return
  3050. if not isinstance(obj, GeometryObject):
  3051. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3052. (_("Expected a GeometryObject, got"), type(obj)))
  3053. return
  3054. obj.multigeo = False
  3055. total_solid_geometry = []
  3056. for tooluid, dict_value in obj.tools.items():
  3057. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3058. # clear the original geometry
  3059. dict_value['solid_geometry'][:] = []
  3060. obj.solid_geometry = deepcopy(total_solid_geometry)
  3061. obj.plot()
  3062. self.should_we_save = True
  3063. self.inform.emit('[success] %s' %
  3064. _("A Geometry object was converted to SingleGeo type."))
  3065. def on_defaults_dict_change(self, field):
  3066. """
  3067. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3068. Edit -> Preferences tab window.
  3069. :param field: the key of the self.defaults dictionary that was changed.
  3070. :return: None
  3071. """
  3072. self.preferencesUiManager.defaults_write_form_field(field=field)
  3073. if field == "units":
  3074. self.set_screen_units(self.defaults['units'])
  3075. def set_screen_units(self, units):
  3076. """
  3077. Set the FlatCAM units on the status bar.
  3078. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3079. :return: None
  3080. """
  3081. self.ui.units_label.setText("[" + units.lower() + "]")
  3082. def on_toggle_units_click(self):
  3083. try:
  3084. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3085. except (TypeError, AttributeError):
  3086. pass
  3087. if self.defaults["units"] == 'MM':
  3088. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3089. else:
  3090. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3091. self.on_toggle_units(no_pref=True)
  3092. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3093. lambda: self.on_toggle_units(no_pref=False))
  3094. def on_toggle_units(self, no_pref=False):
  3095. """
  3096. Callback for the Units radio-button change in the Preferences tab.
  3097. Changes the application's default units adn for the project too.
  3098. If changing the project's units, the change propagates to all of
  3099. the objects in the project.
  3100. :return: None
  3101. """
  3102. self.defaults.report_usage("on_toggle_units")
  3103. if self.toggle_units_ignore:
  3104. return
  3105. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3106. # If option is the same, then ignore
  3107. if new_units == self.defaults["units"].upper():
  3108. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3109. return
  3110. # Keys in self.defaults for which to scale their values
  3111. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3112. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3113. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3114. "gerber_editor_ma_high",
  3115. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3116. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3117. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3118. "excellon_feedrate_probe", "excellon_milling_dia",
  3119. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3120. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3121. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3122. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3123. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3124. "geometry_extracut_length", "geometry_z_pdepth",
  3125. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3126. 'cncjob_tooldia',
  3127. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3128. "tools_paintnewdia",
  3129. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3130. "tools_nccnewdia", "tools_ncc_offset_value",
  3131. "tools_2sided_drilldia",
  3132. "tools_film_boundary", "tools_film_scale_stroke",
  3133. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3134. "tools_cutout_depthperpass",
  3135. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3136. "tools_panelize_spacing_rows",
  3137. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3138. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3139. "tools_transform_buffer_dis",
  3140. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3141. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3142. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3143. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3144. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3145. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3146. "tools_cr_h2h_val", "tools_cr_dh_val",
  3147. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3148. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3149. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3150. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3151. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3152. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3153. "tools_copper_thieving_mask_clearance",
  3154. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3155. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3156. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3157. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3158. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3159. "tools_invert_margin",
  3160. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3161. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3162. def scale_defaults(sfactor):
  3163. for dim in dimensions:
  3164. if dim in [
  3165. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3166. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3167. 'tools_transform_mirror_point'
  3168. ]:
  3169. if self.defaults[dim] is None or self.defaults[dim] == '':
  3170. continue
  3171. try:
  3172. coordinates = self.defaults[dim].split(",")
  3173. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3174. coords_xy[0] *= sfactor
  3175. coords_xy[1] *= sfactor
  3176. self.defaults[dim] = "%.*f, %.*f" % (
  3177. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3178. except Exception as e:
  3179. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3180. elif dim in [
  3181. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3182. ]:
  3183. if self.defaults[dim] is None or self.defaults[dim] == '':
  3184. continue
  3185. try:
  3186. self.defaults[dim] = float(self.defaults[dim])
  3187. tools_diameters = [self.defaults[dim]]
  3188. except ValueError:
  3189. try:
  3190. tools_string = self.defaults[dim].split(",")
  3191. tools_diameters = [eval(a) for a in tools_string if a != '']
  3192. except Exception as e:
  3193. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3194. continue
  3195. self.defaults[dim] = ''
  3196. td_len = len(tools_diameters)
  3197. if td_len > 1:
  3198. for t in range(td_len):
  3199. tools_diameters[t] *= sfactor
  3200. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3201. else:
  3202. tools_diameters[0] *= sfactor
  3203. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3204. elif dim in ['global_gridx', 'global_gridy']:
  3205. # format the number of decimals to the one specified in self.decimals
  3206. try:
  3207. val = float(self.defaults[dim]) * sfactor
  3208. except Exception as e:
  3209. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3210. continue
  3211. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3212. else:
  3213. # the number of decimals for the rest is kept unchanged
  3214. if self.defaults[dim]:
  3215. try:
  3216. val = float(self.defaults[dim]) * sfactor
  3217. except Exception as e:
  3218. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3219. continue
  3220. self.defaults[dim] = val
  3221. # The scaling factor depending on choice of units.
  3222. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3223. # Changing project units. Warn user.
  3224. msgbox = QtWidgets.QMessageBox()
  3225. msgbox.setWindowTitle(_("Toggle Units"))
  3226. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3227. msgbox.setText(_("Changing the units of the project\n"
  3228. "will scale all objects.\n\n"
  3229. "Do you want to continue?"))
  3230. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3231. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3232. msgbox.setDefaultButton(bt_ok)
  3233. msgbox.exec_()
  3234. response = msgbox.clickedButton()
  3235. if response == bt_ok:
  3236. if no_pref is False:
  3237. self.preferencesUiManager.defaults_read_form()
  3238. scale_defaults(factor)
  3239. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3240. self.defaults["units"] = new_units
  3241. # update the defaults from form, some may assume that the conversion is enough and it's not
  3242. self.on_options_app2project()
  3243. # update the objects
  3244. for obj in self.collection.get_list():
  3245. obj.convert_units(new_units)
  3246. # make that the properties stored in the object are also updated
  3247. self.app_obj.object_changed.emit(obj)
  3248. # rebuild the object UI
  3249. obj.build_ui()
  3250. # change this only if the workspace is active
  3251. if self.defaults['global_workspace'] is True:
  3252. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3253. # adjust the grid values on the main toolbar
  3254. val_x = float(self.defaults['global_gridx']) * factor
  3255. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3256. current = self.collection.get_active()
  3257. if current is not None:
  3258. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3259. if not isinstance(current, GeometryObject):
  3260. current.to_form()
  3261. # replot all objects
  3262. self.plot_all()
  3263. # set the status labels to reflect the current FlatCAM units
  3264. self.set_screen_units(new_units)
  3265. # signal to the app that we changed the object properties and it should save the project
  3266. self.should_we_save = True
  3267. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3268. else:
  3269. # Undo toggling
  3270. self.toggle_units_ignore = True
  3271. if self.defaults['units'].upper() == 'MM':
  3272. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3273. else:
  3274. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3275. self.toggle_units_ignore = False
  3276. # store the grid values so they are not changed in the next step
  3277. val_x = float(self.defaults['global_gridx'])
  3278. val_y = float(self.defaults['global_gridy'])
  3279. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3280. self.preferencesUiManager.defaults_read_form()
  3281. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3282. # in self.defaults from the GUI elements but
  3283. # I don't want it for the grid values, so I update them here
  3284. self.defaults['global_gridx'] = val_x
  3285. self.defaults['global_gridy'] = val_y
  3286. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3287. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3288. def on_toggle_axis(self):
  3289. self.defaults.report_usage("on_toggle_axis()")
  3290. if self.toggle_axis is False:
  3291. if self.is_legacy is False:
  3292. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3293. parent=self.plotcanvas.view.scene)
  3294. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3295. parent=self.plotcanvas.view.scene)
  3296. else:
  3297. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3298. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3299. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3300. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3301. self.plotcanvas.canvas.draw()
  3302. self.toggle_axis = True
  3303. else:
  3304. if self.is_legacy is False:
  3305. self.plotcanvas.v_line.parent = None
  3306. self.plotcanvas.h_line.parent = None
  3307. else:
  3308. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3309. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3310. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3311. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3312. self.plotcanvas.canvas.draw()
  3313. self.toggle_axis = False
  3314. def on_toggle_hud(self):
  3315. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3316. def on_toggle_grid_lines(self):
  3317. self.defaults.report_usage("on_toggle_grd_lines()")
  3318. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3319. if tt_settings.contains("theme"):
  3320. theme = tt_settings.value('theme', type=str)
  3321. else:
  3322. theme = 'white'
  3323. if self.toggle_grid_lines is False:
  3324. if self.is_legacy is False:
  3325. if theme == 'white':
  3326. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3327. else:
  3328. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3329. else:
  3330. self.plotcanvas.axes.grid(True)
  3331. try:
  3332. self.plotcanvas.canvas.draw()
  3333. except IndexError:
  3334. pass
  3335. pass
  3336. self.toggle_grid_lines = True
  3337. else:
  3338. if self.is_legacy is False:
  3339. if theme == 'white':
  3340. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3341. else:
  3342. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3343. else:
  3344. self.plotcanvas.axes.grid(False)
  3345. try:
  3346. self.plotcanvas.canvas.draw()
  3347. except IndexError:
  3348. pass
  3349. self.toggle_grid_lines = False
  3350. if self.is_legacy is False:
  3351. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3352. # - perhaps is a bug in VisPy implementation
  3353. if self.grid_status():
  3354. self.app_cursor.enabled = False
  3355. self.app_cursor.enabled = True
  3356. else:
  3357. self.app_cursor.enabled = True
  3358. self.app_cursor.enabled = False
  3359. def on_update_exc_export(self, state):
  3360. """
  3361. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3362. if the update_excellon_cb checkbox is checked
  3363. :param state: state of the checkbox whose signals is tied to his slot
  3364. :return:
  3365. """
  3366. if state:
  3367. # first try to disconnect
  3368. try:
  3369. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3370. disconnect(self.on_excellon_format_changed)
  3371. except TypeError:
  3372. pass
  3373. try:
  3374. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3375. disconnect(self.on_excellon_format_changed)
  3376. except TypeError:
  3377. pass
  3378. try:
  3379. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3380. disconnect(self.on_excellon_format_changed)
  3381. except TypeError:
  3382. pass
  3383. try:
  3384. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3385. disconnect(self.on_excellon_format_changed)
  3386. except TypeError:
  3387. pass
  3388. try:
  3389. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3390. disconnect(self.on_excellon_zeros_changed)
  3391. except TypeError:
  3392. pass
  3393. try:
  3394. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3395. disconnect(self.on_excellon_zeros_changed)
  3396. except TypeError:
  3397. pass
  3398. # the connect them
  3399. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3400. self.on_excellon_format_changed)
  3401. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3402. self.on_excellon_format_changed)
  3403. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3404. self.on_excellon_format_changed)
  3405. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3406. self.on_excellon_format_changed)
  3407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3408. self.on_excellon_zeros_changed)
  3409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3410. self.on_excellon_units_changed)
  3411. else:
  3412. # disconnect the signals
  3413. try:
  3414. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3415. disconnect(self.on_excellon_format_changed)
  3416. except TypeError:
  3417. pass
  3418. try:
  3419. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3420. disconnect(self.on_excellon_format_changed)
  3421. except TypeError:
  3422. pass
  3423. try:
  3424. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3425. disconnect(self.on_excellon_format_changed)
  3426. except TypeError:
  3427. pass
  3428. try:
  3429. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3430. disconnect(self.on_excellon_format_changed)
  3431. except TypeError:
  3432. pass
  3433. try:
  3434. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3435. disconnect(self.on_excellon_zeros_changed)
  3436. except TypeError:
  3437. pass
  3438. try:
  3439. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3440. disconnect(self.on_excellon_zeros_changed)
  3441. except TypeError:
  3442. pass
  3443. def on_excellon_format_changed(self):
  3444. """
  3445. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3446. :return: None
  3447. """
  3448. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3449. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3450. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3451. )
  3452. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3453. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3454. )
  3455. else:
  3456. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3457. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3458. )
  3459. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3460. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3461. )
  3462. def on_excellon_zeros_changed(self):
  3463. """
  3464. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3465. :return: None
  3466. """
  3467. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3468. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3469. )
  3470. def on_excellon_units_changed(self):
  3471. """
  3472. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3473. :return: None
  3474. """
  3475. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3476. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3477. )
  3478. self.on_excellon_format_changed()
  3479. def on_film_color_entry(self):
  3480. self.defaults['tools_film_color'] = \
  3481. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3482. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3483. "background-color:%s;"
  3484. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3485. )
  3486. def on_film_color_button(self):
  3487. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3488. c_dialog = QtWidgets.QColorDialog()
  3489. film_color = c_dialog.getColor(initial=current_color)
  3490. if film_color.isValid() is False:
  3491. return
  3492. # if new color is different then mark that the Preferences are changed
  3493. if film_color != current_color:
  3494. self.preferencesUiManager.on_preferences_edited()
  3495. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3496. "background-color:%s;"
  3497. "border-color: dimgray" % str(film_color.name())
  3498. )
  3499. new_val_sel = str(film_color.name())
  3500. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3501. self.defaults['tools_film_color'] = new_val_sel
  3502. def on_qrcode_fill_color_entry(self):
  3503. self.defaults['tools_qrcode_fill_color'] = \
  3504. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3505. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3506. "background-color:%s;"
  3507. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3508. )
  3509. def on_qrcode_fill_color_button(self):
  3510. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3511. c_dialog = QtWidgets.QColorDialog()
  3512. fill_color = c_dialog.getColor(initial=current_color)
  3513. if fill_color.isValid() is False:
  3514. return
  3515. # if new color is different then mark that the Preferences are changed
  3516. if fill_color != current_color:
  3517. self.preferencesUiManager.on_preferences_edited()
  3518. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3519. "background-color:%s;"
  3520. "border-color: dimgray" % str(fill_color.name())
  3521. )
  3522. new_val_sel = str(fill_color.name())
  3523. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3524. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3525. def on_qrcode_back_color_entry(self):
  3526. self.defaults['tools_qrcode_back_color'] = \
  3527. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3528. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3529. "background-color:%s;"
  3530. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3531. )
  3532. def on_qrcode_back_color_button(self):
  3533. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3534. c_dialog = QtWidgets.QColorDialog()
  3535. back_color = c_dialog.getColor(initial=current_color)
  3536. if back_color.isValid() is False:
  3537. return
  3538. # if new color is different then mark that the Preferences are changed
  3539. if back_color != current_color:
  3540. self.preferencesUiManager.on_preferences_edited()
  3541. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3542. "background-color:%s;"
  3543. "border-color: dimgray" % str(back_color.name())
  3544. )
  3545. new_val_sel = str(back_color.name())
  3546. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3547. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3548. def on_tab_rmb_click(self, checked):
  3549. self.ui.notebook.set_detachable(val=checked)
  3550. self.defaults["global_tabs_detachable"] = checked
  3551. self.ui.plot_tab_area.set_detachable(val=checked)
  3552. self.defaults["global_tabs_detachable"] = checked
  3553. def on_tab_setup_context_menu(self):
  3554. initial_checked = self.defaults["global_tabs_detachable"]
  3555. action_name = str(_("Detachable Tabs"))
  3556. action = QtWidgets.QAction(self)
  3557. action.setCheckable(True)
  3558. action.setText(action_name)
  3559. action.setChecked(initial_checked)
  3560. self.ui.notebook.tabBar.addAction(action)
  3561. self.ui.plot_tab_area.tabBar.addAction(action)
  3562. try:
  3563. action.triggered.disconnect()
  3564. except TypeError:
  3565. pass
  3566. action.triggered.connect(self.on_tab_rmb_click)
  3567. def on_deselect_all(self):
  3568. self.collection.set_all_inactive()
  3569. self.delete_selection_shape()
  3570. def on_workspace_modified(self):
  3571. # self.save_defaults(silent=True)
  3572. self.plotcanvas.delete_workspace()
  3573. self.preferencesUiManager.defaults_read_form()
  3574. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3575. def on_workspace(self):
  3576. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3577. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3578. self.inform.emit(_("Workspace enabled."))
  3579. else:
  3580. self.plotcanvas.delete_workspace()
  3581. self.inform.emit(_("Workspace disabled."))
  3582. self.preferencesUiManager.defaults_read_form()
  3583. # self.save_defaults(silent=True)
  3584. def on_workspace_toggle(self):
  3585. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3586. try:
  3587. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3588. except TypeError:
  3589. pass
  3590. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3591. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3592. self.on_workspace()
  3593. def on_cursor_type(self, val):
  3594. """
  3595. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3596. :return: None
  3597. """
  3598. self.app_cursor.enabled = False
  3599. if val == 'small':
  3600. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3601. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3602. self.app_cursor = self.plotcanvas.new_cursor()
  3603. else:
  3604. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3605. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3606. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3607. if self.ui.grid_snap_btn.isChecked():
  3608. self.app_cursor.enabled = True
  3609. else:
  3610. self.app_cursor.enabled = False
  3611. def on_tool_add_keypress(self):
  3612. # ## Current application units in Upper Case
  3613. self.units = self.defaults['units'].upper()
  3614. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3615. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3616. if notebook_widget_name == 'selected_tab':
  3617. if self.collection.get_active().kind == 'geometry':
  3618. # Tool add works for Geometry only if Advanced is True in Preferences
  3619. if self.defaults["global_app_level"] == 'a':
  3620. tool_add_popup = FCInputDialog(title="New Tool ...",
  3621. text='Enter a Tool Diameter:',
  3622. min=0.0000, max=99.9999, decimals=4)
  3623. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3624. val, ok = tool_add_popup.get_value()
  3625. if ok:
  3626. if float(val) == 0:
  3627. self.inform.emit('[WARNING_NOTCL] %s' %
  3628. _("Please enter a tool diameter with non-zero value, in Float format."))
  3629. return
  3630. self.collection.get_active().on_tool_add(dia=float(val))
  3631. else:
  3632. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3633. else:
  3634. msgbox = QtWidgets.QMessageBox()
  3635. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3636. "Go to Preferences -> General - Show Advanced Options."))
  3637. msgbox.setWindowTitle("Tool adding ...")
  3638. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3639. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3640. msgbox.setDefaultButton(bt_ok)
  3641. msgbox.exec_()
  3642. # work only if the notebook tab on focus is the Tools_Tab
  3643. if notebook_widget_name == 'tool_tab':
  3644. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3645. # and only if the tool is NCC Tool
  3646. if tool_widget == self.ncclear_tool.toolName:
  3647. self.ncclear_tool.on_add_tool_by_key()
  3648. # and only if the tool is Paint Area Tool
  3649. elif tool_widget == self.paint_tool.toolName:
  3650. self.paint_tool.on_add_tool_by_key()
  3651. # and only if the tool is Solder Paste Dispensing Tool
  3652. elif tool_widget == self.paste_tool.toolName:
  3653. self.paste_tool.on_add_tool_by_key()
  3654. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3655. # See description below.
  3656. def on_delete_keypress(self):
  3657. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3658. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3659. if notebook_widget_name == 'selected_tab':
  3660. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3661. self.collection.get_active().on_tool_delete()
  3662. # work only if the notebook tab on focus is the Tools_Tab
  3663. elif notebook_widget_name == 'tool_tab':
  3664. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3665. # and only if the tool is NCC Tool
  3666. if tool_widget == self.ncclear_tool.toolName:
  3667. self.ncclear_tool.on_tool_delete()
  3668. # and only if the tool is Paint Tool
  3669. elif tool_widget == self.paint_tool.toolName:
  3670. self.paint_tool.on_tool_delete()
  3671. # and only if the tool is Solder Paste Dispensing Tool
  3672. elif tool_widget == self.paste_tool.toolName:
  3673. self.paste_tool.on_tool_delete()
  3674. else:
  3675. self.on_delete()
  3676. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3677. # some screens you have to be careful where you hover with your mouse.
  3678. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3679. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3680. # Complicated, I know :)
  3681. def on_delete(self, force_deletion=False):
  3682. """
  3683. Delete the currently selected FlatCAMObjs.
  3684. :param force_deletion: used by Tcl command
  3685. :return: None
  3686. """
  3687. self.defaults.report_usage("on_delete()")
  3688. response = None
  3689. bt_ok = None
  3690. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3691. # a geometry object before we update it.
  3692. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3693. and self.grb_editor.editor_active is False:
  3694. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3695. msgbox = QtWidgets.QMessageBox()
  3696. msgbox.setWindowTitle(_("Delete objects"))
  3697. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3698. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3699. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3700. "the selected objects?"))
  3701. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3702. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3703. msgbox.setDefaultButton(bt_ok)
  3704. msgbox.exec_()
  3705. response = msgbox.clickedButton()
  3706. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3707. response = bt_ok
  3708. if response == bt_ok:
  3709. if self.collection.get_active():
  3710. self.log.debug("App.on_delete()")
  3711. for obj_active in self.collection.get_selected():
  3712. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3713. if obj_active.kind == 'gerber':
  3714. for el in obj_active.mark_shapes:
  3715. obj_active.mark_shapes[el].clear(update=True)
  3716. obj_active.mark_shapes[el].enabled = False
  3717. # obj_active.mark_shapes[el] = None
  3718. del el
  3719. elif isinstance(obj_active, CNCJobObject):
  3720. try:
  3721. obj_active.text_col.enabled = False
  3722. del obj_active.text_col
  3723. obj_active.annotation.clear(update=True)
  3724. del obj_active.annotation
  3725. except AttributeError as e:
  3726. log.debug(
  3727. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3728. )
  3729. while self.collection.get_selected():
  3730. self.delete_first_selected()
  3731. self.inform.emit('%s...' % _("Object(s) deleted"))
  3732. # make sure that the selection shape is deleted, too
  3733. self.delete_selection_shape()
  3734. # if there are no longer objects delete also the exclusion areas shapes
  3735. if not self.collection.get_list():
  3736. self.exc_areas.clear_shapes()
  3737. else:
  3738. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3739. else:
  3740. self.inform.emit(_("Save the work in Editor and try again ..."))
  3741. def delete_first_selected(self):
  3742. # Keep this for later
  3743. try:
  3744. sel_obj = self.collection.get_active()
  3745. name = sel_obj.options["name"]
  3746. isPlotted = sel_obj.options["plot"]
  3747. except AttributeError:
  3748. self.log.debug("Nothing selected for deletion")
  3749. return
  3750. if self.is_legacy is True:
  3751. # Remove plot only if the object was plotted otherwise delaxes will fail
  3752. if isPlotted:
  3753. try:
  3754. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3755. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3756. except Exception as e:
  3757. log.debug("App.delete_first_selected() --> %s" % str(e))
  3758. self.plotcanvas.auto_adjust_axes()
  3759. # Remove from dictionary
  3760. self.collection.delete_active()
  3761. # Clear form
  3762. self.setup_component_editor()
  3763. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3764. def on_set_origin(self):
  3765. """
  3766. Set the origin to the left mouse click position
  3767. :return: None
  3768. """
  3769. # display the message for the user
  3770. # and ask him to click on the desired position
  3771. self.defaults.report_usage("on_set_origin()")
  3772. def origin_replot():
  3773. def worker_task():
  3774. with self.proc_container.new('%s...' % _("Plotting")):
  3775. for obj in self.collection.get_list():
  3776. obj.plot()
  3777. self.plotcanvas.fit_view()
  3778. if self.is_legacy:
  3779. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3780. else:
  3781. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3782. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3783. self.inform.emit(_('Click to set the origin ...'))
  3784. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3785. # first disconnect it as it may have been used by something else
  3786. try:
  3787. self.replot_signal.disconnect()
  3788. except TypeError:
  3789. pass
  3790. self.replot_signal[list].connect(origin_replot)
  3791. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3792. """
  3793. :param event:
  3794. :param location:
  3795. :param noplot:
  3796. :param use_thread:
  3797. :return:
  3798. """
  3799. noplot_sig = noplot
  3800. def worker_task():
  3801. with self.proc_container.new(_("Setting Origin...")):
  3802. obj_list = self.collection.get_list()
  3803. for obj in obj_list:
  3804. obj.offset((x, y))
  3805. self.app_obj.object_changed.emit(obj)
  3806. # Update the object bounding box options
  3807. a, b, c, d = obj.bounds()
  3808. obj.options['xmin'] = a
  3809. obj.options['ymin'] = b
  3810. obj.options['xmax'] = c
  3811. obj.options['ymax'] = d
  3812. self.inform.emit('[success] %s...' % _('Origin set'))
  3813. for obj in obj_list:
  3814. out_name = obj.options["name"]
  3815. if obj.kind == 'gerber':
  3816. obj.source_file = self.export_gerber(
  3817. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3818. elif obj.kind == 'excellon':
  3819. obj.source_file = self.export_excellon(
  3820. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3821. if noplot_sig is False:
  3822. self.replot_signal.emit([])
  3823. if location is not None:
  3824. if len(location) != 2:
  3825. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3826. return 'fail'
  3827. x, y = location
  3828. if use_thread is True:
  3829. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3830. else:
  3831. worker_task()
  3832. self.should_we_save = True
  3833. return
  3834. if event is not None and event.button == 1:
  3835. if self.is_legacy is False:
  3836. event_pos = event.pos
  3837. else:
  3838. event_pos = (event.xdata, event.ydata)
  3839. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3840. if self.grid_status():
  3841. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3842. else:
  3843. pos = pos_canvas
  3844. x = 0 - pos[0]
  3845. y = 0 - pos[1]
  3846. if use_thread is True:
  3847. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3848. else:
  3849. worker_task()
  3850. self.should_we_save = True
  3851. def on_move2origin(self, use_thread=True):
  3852. """
  3853. Move selected objects to origin.
  3854. :param use_thread: Control if to use threaded operation. Boolean.
  3855. :return:
  3856. """
  3857. def worker_task():
  3858. with self.proc_container.new(_("Moving to Origin...")):
  3859. obj_list = self.collection.get_selected()
  3860. if not obj_list:
  3861. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3862. return
  3863. xminlist = []
  3864. yminlist = []
  3865. # first get a bounding box to fit all
  3866. for obj in obj_list:
  3867. xmin, ymin, xmax, ymax = obj.bounds()
  3868. xminlist.append(xmin)
  3869. yminlist.append(ymin)
  3870. # get the minimum x,y for all objects selected
  3871. x = min(xminlist)
  3872. y = min(yminlist)
  3873. for obj in obj_list:
  3874. obj.offset((-x, -y))
  3875. self.app_obj.object_changed.emit(obj)
  3876. # Update the object bounding box options
  3877. a, b, c, d = obj.bounds()
  3878. obj.options['xmin'] = a
  3879. obj.options['ymin'] = b
  3880. obj.options['xmax'] = c
  3881. obj.options['ymax'] = d
  3882. for obj in obj_list:
  3883. obj.plot()
  3884. for obj in obj_list:
  3885. out_name = obj.options["name"]
  3886. if obj.kind == 'gerber':
  3887. obj.source_file = self.export_gerber(
  3888. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3889. elif obj.kind == 'excellon':
  3890. obj.source_file = self.export_excellon(
  3891. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3892. self.inform.emit('[success] %s...' % _('Origin set'))
  3893. if use_thread is True:
  3894. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3895. else:
  3896. worker_task()
  3897. self.should_we_save = True
  3898. def on_jump_to(self, custom_location=None, fit_center=True):
  3899. """
  3900. Jump to a location by setting the mouse cursor location.
  3901. :param custom_location: Jump to a specified point. (x, y) tuple.
  3902. :param fit_center: If to fit view. Boolean.
  3903. :return:
  3904. """
  3905. self.defaults.report_usage("on_jump_to()")
  3906. if not custom_location:
  3907. dia_box_location = None
  3908. try:
  3909. dia_box_location = eval(self.clipboard.text())
  3910. except Exception:
  3911. pass
  3912. if type(dia_box_location) == tuple:
  3913. dia_box_location = str(dia_box_location)
  3914. else:
  3915. dia_box_location = None
  3916. # dia_box = Dialog_box(title=_("Jump to ..."),
  3917. # label=_("Enter the coordinates in format X,Y:"),
  3918. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3919. # initial_text=dia_box_location)
  3920. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3921. label=_("Enter the coordinates in format X,Y:"),
  3922. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3923. initial_text=dia_box_location,
  3924. reference=self.defaults['global_jump_ref'])
  3925. if dia_box.ok is True:
  3926. try:
  3927. location = eval(dia_box.location)
  3928. if not isinstance(location, tuple):
  3929. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3930. return
  3931. if dia_box.reference == 'rel':
  3932. rel_x = self.mouse[0] + location[0]
  3933. rel_y = self.mouse[1] + location[1]
  3934. location = (rel_x, rel_y)
  3935. self.defaults['global_jump_ref'] = dia_box.reference
  3936. except Exception:
  3937. return
  3938. else:
  3939. return
  3940. else:
  3941. location = custom_location
  3942. self.jump_signal.emit(location)
  3943. if fit_center:
  3944. self.plotcanvas.fit_center(loc=location)
  3945. cursor = QtGui.QCursor()
  3946. if self.is_legacy is False:
  3947. # I don't know where those differences come from but they are constant for the current
  3948. # execution of the application and they are multiples of a value around 0.0263mm.
  3949. # In a random way sometimes they are more sometimes they are less
  3950. # if units == 'MM':
  3951. # cal_factor = 0.0263
  3952. # else:
  3953. # cal_factor = 0.0263 / 25.4
  3954. cal_location = (location[0], location[1])
  3955. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3956. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3957. j_pos = (
  3958. int(canvas_origin.x() + round(jump_loc[0])),
  3959. int(canvas_origin.y() + round(jump_loc[1]))
  3960. )
  3961. cursor.setPos(j_pos[0], j_pos[1])
  3962. else:
  3963. # find the canvas origin which is in the top left corner
  3964. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3965. # determine the coordinates for the lowest left point of the canvas
  3966. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3967. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3968. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3969. # canvas) and the point (width, height) is in the top-right location
  3970. loc = self.plotcanvas.axes.transData.transform_point(location)
  3971. j_pos = (
  3972. int(x0 + loc[0]),
  3973. int(y0 - loc[1])
  3974. )
  3975. cursor.setPos(j_pos[0], j_pos[1])
  3976. self.plotcanvas.mouse = [location[0], location[1]]
  3977. if self.defaults["global_cursor_color_enabled"] is True:
  3978. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3979. else:
  3980. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3981. if self.grid_status():
  3982. # Update cursor
  3983. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3984. symbol='++', edge_color=self.cursor_color_3D,
  3985. edge_width=self.defaults["global_cursor_width"],
  3986. size=self.defaults["global_cursor_size"])
  3987. # Set the relative position label
  3988. dx = location[0] - float(self.rel_point1[0])
  3989. dy = location[1] - float(self.rel_point1[1])
  3990. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3991. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3992. # # Set the position label
  3993. #
  3994. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3995. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3996. units = self.defaults["units"].lower()
  3997. self.plotcanvas.text_hud.text = \
  3998. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3999. dx, units, dy, units, location[0], units, location[1], units)
  4000. self.inform.emit('[success] %s' % _("Done."))
  4001. return location
  4002. def on_locate(self, obj, fit_center=True):
  4003. """
  4004. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4005. :param obj: The object on which to locate certain points
  4006. :param fit_center: If to fit view. Boolean.
  4007. :return: A point location. (x, y) tuple.
  4008. """
  4009. self.defaults.report_usage("on_locate()")
  4010. if obj is None:
  4011. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4012. return 'fail'
  4013. class DialogBoxChoice(QtWidgets.QDialog):
  4014. def __init__(self, title=None, icon=None, choice='bl'):
  4015. """
  4016. :param title: string with the window title
  4017. """
  4018. super(DialogBoxChoice, self).__init__()
  4019. self.ok = False
  4020. self.setWindowIcon(icon)
  4021. self.setWindowTitle(str(title))
  4022. self.form = QtWidgets.QFormLayout(self)
  4023. self.ref_radio = RadioSet([
  4024. {"label": _("Bottom-Left"), "value": "bl"},
  4025. {"label": _("Top-Left"), "value": "tl"},
  4026. {"label": _("Bottom-Right"), "value": "br"},
  4027. {"label": _("Top-Right"), "value": "tr"},
  4028. {"label": _("Center"), "value": "c"}
  4029. ], orientation='vertical', stretch=False)
  4030. self.ref_radio.set_value(choice)
  4031. self.form.addRow(self.ref_radio)
  4032. self.button_box = QtWidgets.QDialogButtonBox(
  4033. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4034. Qt.Horizontal, parent=self)
  4035. self.form.addRow(self.button_box)
  4036. self.button_box.accepted.connect(self.accept)
  4037. self.button_box.rejected.connect(self.reject)
  4038. if self.exec_() == QtWidgets.QDialog.Accepted:
  4039. self.ok = True
  4040. self.location_point = self.ref_radio.get_value()
  4041. else:
  4042. self.ok = False
  4043. self.location_point = None
  4044. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4045. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4046. choice=self.defaults['global_locate_pt'])
  4047. if dia_box.ok is True:
  4048. try:
  4049. location_point = dia_box.location_point
  4050. self.defaults['global_locate_pt'] = dia_box.location_point
  4051. except Exception:
  4052. return
  4053. else:
  4054. return
  4055. loc_b = obj.bounds()
  4056. if location_point == 'bl':
  4057. location = (loc_b[0], loc_b[1])
  4058. elif location_point == 'tl':
  4059. location = (loc_b[0], loc_b[3])
  4060. elif location_point == 'br':
  4061. location = (loc_b[2], loc_b[1])
  4062. elif location_point == 'tr':
  4063. location = (loc_b[2], loc_b[3])
  4064. else:
  4065. # center
  4066. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4067. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4068. location = (cx, cy)
  4069. self.locate_signal.emit(location, location_point)
  4070. if fit_center:
  4071. self.plotcanvas.fit_center(loc=location)
  4072. cursor = QtGui.QCursor()
  4073. if self.is_legacy is False:
  4074. # I don't know where those differences come from but they are constant for the current
  4075. # execution of the application and they are multiples of a value around 0.0263mm.
  4076. # In a random way sometimes they are more sometimes they are less
  4077. # if units == 'MM':
  4078. # cal_factor = 0.0263
  4079. # else:
  4080. # cal_factor = 0.0263 / 25.4
  4081. cal_location = (location[0], location[1])
  4082. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4083. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4084. j_pos = (
  4085. int(canvas_origin.x() + round(jump_loc[0])),
  4086. int(canvas_origin.y() + round(jump_loc[1]))
  4087. )
  4088. cursor.setPos(j_pos[0], j_pos[1])
  4089. else:
  4090. # find the canvas origin which is in the top left corner
  4091. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4092. # determine the coordinates for the lowest left point of the canvas
  4093. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4094. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4095. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4096. # canvas) and the point (width, height) is in the top-right location
  4097. loc = self.plotcanvas.axes.transData.transform_point(location)
  4098. j_pos = (
  4099. int(x0 + loc[0]),
  4100. int(y0 - loc[1])
  4101. )
  4102. cursor.setPos(j_pos[0], j_pos[1])
  4103. self.plotcanvas.mouse = [location[0], location[1]]
  4104. if self.defaults["global_cursor_color_enabled"] is True:
  4105. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4106. else:
  4107. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4108. if self.grid_status():
  4109. # Update cursor
  4110. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4111. symbol='++', edge_color=self.cursor_color_3D,
  4112. edge_width=self.defaults["global_cursor_width"],
  4113. size=self.defaults["global_cursor_size"])
  4114. # Set the relative position label
  4115. self.dx = location[0] - float(self.rel_point1[0])
  4116. self.dy = location[1] - float(self.rel_point1[1])
  4117. # Set the position label
  4118. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4119. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4120. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4121. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4122. units = self.defaults["units"].lower()
  4123. self.plotcanvas.text_hud.text = \
  4124. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4125. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4126. self.inform.emit('[success] %s' % _("Done."))
  4127. return location
  4128. def on_copy_command(self):
  4129. """
  4130. Will copy a selection of objects, creating new objects.
  4131. :return:
  4132. """
  4133. self.defaults.report_usage("on_copy_command()")
  4134. def initialize(obj_init, app):
  4135. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4136. try:
  4137. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4138. except AttributeError:
  4139. pass
  4140. try:
  4141. obj_init.apertures = deepcopy(obj.apertures)
  4142. except AttributeError:
  4143. pass
  4144. try:
  4145. if obj.tools:
  4146. obj_init.tools = deepcopy(obj.tools)
  4147. except Exception as err:
  4148. log.debug("App.on_copy_command() --> %s" % str(err))
  4149. try:
  4150. obj_init.source_file = deepcopy(obj.source_file)
  4151. except (AttributeError, TypeError):
  4152. pass
  4153. def initialize_excellon(obj_init, app):
  4154. obj_init.source_file = deepcopy(obj.source_file)
  4155. obj_init.tools = deepcopy(obj.tools)
  4156. # drills are offset, so they need to be deep copied
  4157. obj_init.drills = deepcopy(obj.drills)
  4158. # slots are offset, so they need to be deep copied
  4159. obj_init.slots = deepcopy(obj.slots)
  4160. obj_init.create_geometry()
  4161. def initialize_script(obj_init, app_obj):
  4162. obj_init.source_file = deepcopy(obj.source_file)
  4163. def initialize_document(obj_init, app_obj):
  4164. obj_init.source_file = deepcopy(obj.source_file)
  4165. for obj in self.collection.get_selected():
  4166. obj_name = obj.options["name"]
  4167. try:
  4168. if isinstance(obj, ExcellonObject):
  4169. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4170. elif isinstance(obj, GerberObject):
  4171. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4172. elif isinstance(obj, GeometryObject):
  4173. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4174. elif isinstance(obj, ScriptObject):
  4175. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4176. elif isinstance(obj, DocumentObject):
  4177. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4178. except Exception as e:
  4179. return "Operation failed: %s" % str(e)
  4180. def on_copy_object2(self, custom_name):
  4181. def initialize_geometry(obj_init, app):
  4182. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4183. try:
  4184. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4185. except AttributeError:
  4186. pass
  4187. try:
  4188. obj_init.apertures = deepcopy(obj.apertures)
  4189. except AttributeError:
  4190. pass
  4191. try:
  4192. if obj.tools:
  4193. obj_init.tools = deepcopy(obj.tools)
  4194. except Exception as ee:
  4195. log.debug("on_copy_object2() --> %s" % str(ee))
  4196. def initialize_gerber(obj_init, app):
  4197. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4198. obj_init.apertures = deepcopy(obj.apertures)
  4199. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4200. def initialize_excellon(obj_init, app):
  4201. obj_init.tools = deepcopy(obj.tools)
  4202. # drills are offset, so they need to be deep copied
  4203. obj_init.drills = deepcopy(obj.drills)
  4204. # slots are offset, so they need to be deep copied
  4205. obj_init.slots = deepcopy(obj.slots)
  4206. obj_init.create_geometry()
  4207. for obj in self.collection.get_selected():
  4208. obj_name = obj.options["name"]
  4209. try:
  4210. if isinstance(obj, ExcellonObject):
  4211. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4212. elif isinstance(obj, GerberObject):
  4213. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4214. elif isinstance(obj, GeometryObject):
  4215. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4216. except Exception as er:
  4217. return "Operation failed: %s" % str(er)
  4218. def on_rename_object(self, text):
  4219. """
  4220. Will rename an object.
  4221. :param text: New name for the object.
  4222. :return:
  4223. """
  4224. self.defaults.report_usage("on_rename_object()")
  4225. named_obj = self.collection.get_active()
  4226. for obj in named_obj:
  4227. if obj is list:
  4228. self.on_rename_object(text)
  4229. else:
  4230. try:
  4231. obj.options['name'] = text
  4232. except Exception as e:
  4233. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4234. def convert_any2geo(self):
  4235. """
  4236. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4237. :return:
  4238. """
  4239. self.defaults.report_usage("convert_any2geo()")
  4240. def initialize(obj_init, app):
  4241. obj_init.solid_geometry = obj.solid_geometry
  4242. try:
  4243. obj_init.follow_geometry = obj.follow_geometry
  4244. except AttributeError:
  4245. pass
  4246. try:
  4247. obj_init.apertures = obj.apertures
  4248. except AttributeError:
  4249. pass
  4250. try:
  4251. if obj.tools:
  4252. obj_init.tools = obj.tools
  4253. except AttributeError:
  4254. pass
  4255. def initialize_excellon(obj_init, app):
  4256. # objs = self.collection.get_selected()
  4257. # GeometryObject.merge(objs, obj)
  4258. solid_geo = []
  4259. for tool in obj.tools:
  4260. for geo in obj.tools[tool]['solid_geometry']:
  4261. solid_geo.append(geo)
  4262. obj_init.solid_geometry = deepcopy(solid_geo)
  4263. if not self.collection.get_selected():
  4264. log.warning("App.convert_any2geo --> No object selected")
  4265. self.inform.emit('[WARNING_NOTCL] %s' %
  4266. _("No object is selected. Select an object and try again."))
  4267. return
  4268. for obj in self.collection.get_selected():
  4269. obj_name = obj.options["name"]
  4270. try:
  4271. if isinstance(obj, ExcellonObject):
  4272. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4273. else:
  4274. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4275. except Exception as e:
  4276. return "Operation failed: %s" % str(e)
  4277. def convert_any2gerber(self):
  4278. """
  4279. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4280. :return:
  4281. """
  4282. self.defaults.report_usage("convert_any2gerber()")
  4283. def initialize_geometry(obj_init, app):
  4284. apertures = {}
  4285. apid = 0
  4286. apertures[str(apid)] = {}
  4287. apertures[str(apid)]['geometry'] = []
  4288. for obj_orig in obj.solid_geometry:
  4289. new_elem = {}
  4290. new_elem['solid'] = obj_orig
  4291. try:
  4292. new_elem['follow'] = obj_orig.exterior
  4293. except AttributeError:
  4294. pass
  4295. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4296. apertures[str(apid)]['size'] = 0.0
  4297. apertures[str(apid)]['type'] = 'C'
  4298. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4299. obj_init.apertures = deepcopy(apertures)
  4300. def initialize_excellon(obj_init, app):
  4301. apertures = {}
  4302. apid = 10
  4303. for tool in obj.tools:
  4304. apertures[str(apid)] = {}
  4305. apertures[str(apid)]['geometry'] = []
  4306. for geo in obj.tools[tool]['solid_geometry']:
  4307. new_el = {}
  4308. new_el['solid'] = geo
  4309. new_el['follow'] = geo.exterior
  4310. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4311. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4312. apertures[str(apid)]['type'] = 'C'
  4313. apid += 1
  4314. # create solid_geometry
  4315. solid_geometry = []
  4316. for apid in apertures:
  4317. for geo_el in apertures[apid]['geometry']:
  4318. solid_geometry.append(geo_el['solid'])
  4319. solid_geometry = MultiPolygon(solid_geometry)
  4320. solid_geometry = solid_geometry.buffer(0.0000001)
  4321. obj_init.solid_geometry = deepcopy(solid_geometry)
  4322. obj_init.apertures = deepcopy(apertures)
  4323. # clear the working objects (perhaps not necessary due of Python GC)
  4324. apertures.clear()
  4325. if not self.collection.get_selected():
  4326. log.warning("App.convert_any2gerber --> No object selected")
  4327. self.inform.emit('[WARNING_NOTCL] %s' %
  4328. _("No object is selected. Select an object and try again."))
  4329. return
  4330. for obj in self.collection.get_selected():
  4331. obj_name = obj.options["name"]
  4332. try:
  4333. if isinstance(obj, ExcellonObject):
  4334. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4335. elif isinstance(obj, GeometryObject):
  4336. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4337. else:
  4338. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4339. except Exception as e:
  4340. return "Operation failed: %s" % str(e)
  4341. def abort_all_tasks(self):
  4342. """
  4343. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4344. on the first possible occasion.
  4345. :return:
  4346. """
  4347. if self.abort_flag is False:
  4348. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4349. self.abort_flag = True
  4350. self.cleanup.emit()
  4351. def app_is_idle(self):
  4352. if self.abort_flag:
  4353. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4354. self.abort_flag = False
  4355. def on_selectall(self):
  4356. """
  4357. Will draw a selection box shape around the selected objects.
  4358. :return:
  4359. """
  4360. self.defaults.report_usage("on_selectall()")
  4361. # delete the possible selection box around a possible selected object
  4362. self.delete_selection_shape()
  4363. for name in self.collection.get_names():
  4364. self.collection.set_active(name)
  4365. curr_sel_obj = self.collection.get_by_name(name)
  4366. # create the selection box around the selected object
  4367. if self.defaults['global_selection_shape'] is True:
  4368. self.draw_selection_shape(curr_sel_obj)
  4369. def on_preferences(self):
  4370. """
  4371. Adds the Preferences in a Tab in Plot Area
  4372. :return:
  4373. """
  4374. # add the tab if it was closed
  4375. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4376. # delete the absolute and relative position and messages in the infobar
  4377. self.ui.position_label.setText("")
  4378. # self.ui.rel_position_label.setText("")
  4379. # Switch plot_area to preferences page
  4380. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4381. # self.ui.show()
  4382. # detect changes in the preferences
  4383. for idx in range(self.ui.pref_tab_area.count()):
  4384. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4385. try:
  4386. try:
  4387. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4388. except (TypeError, AttributeError):
  4389. pass
  4390. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4391. except AttributeError:
  4392. pass
  4393. try:
  4394. try:
  4395. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4396. except (TypeError, AttributeError):
  4397. pass
  4398. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4399. except AttributeError:
  4400. pass
  4401. try:
  4402. try:
  4403. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4404. except (TypeError, AttributeError):
  4405. pass
  4406. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4407. except AttributeError:
  4408. pass
  4409. try:
  4410. try:
  4411. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4412. except (TypeError, AttributeError):
  4413. pass
  4414. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4415. except AttributeError:
  4416. pass
  4417. try:
  4418. try:
  4419. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4420. except (TypeError, AttributeError):
  4421. pass
  4422. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4423. except AttributeError:
  4424. pass
  4425. def on_tools_database(self, source='app'):
  4426. """
  4427. Adds the Tools Database in a Tab in Plot Area.
  4428. :return:
  4429. """
  4430. for idx in range(self.ui.plot_tab_area.count()):
  4431. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4432. # there can be only one instance of Tools Database at one time
  4433. return
  4434. if source == 'app':
  4435. self.tools_db_tab = ToolsDB2(
  4436. app=self,
  4437. parent=self.ui,
  4438. callback_on_edited=self.on_tools_db_edited,
  4439. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4440. )
  4441. elif source == 'ncc':
  4442. self.tools_db_tab = ToolsDB2(
  4443. app=self,
  4444. parent=self.ui,
  4445. callback_on_edited=self.on_tools_db_edited,
  4446. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4447. )
  4448. elif source == 'paint':
  4449. self.tools_db_tab = ToolsDB2(
  4450. app=self,
  4451. parent=self.ui,
  4452. callback_on_edited=self.on_tools_db_edited,
  4453. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4454. )
  4455. # add the tab if it was closed
  4456. try:
  4457. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4458. self.tools_db_tab.setObjectName("database_tab")
  4459. except Exception as e:
  4460. log.debug("App.on_tools_database() --> %s" % str(e))
  4461. return
  4462. # delete the absolute and relative position and messages in the infobar
  4463. self.ui.position_label.setText("")
  4464. # self.ui.rel_position_label.setText("")
  4465. # Switch plot_area to preferences page
  4466. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4467. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4468. self.tools_db_tab.ui_connect()
  4469. def on_tools_db_edited(self):
  4470. """
  4471. Executed whenever a tool is edited in Tools Database.
  4472. Will color the text of the Tools Database tab to Red color.
  4473. :return:
  4474. """
  4475. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4476. for idx in range(self.ui.plot_tab_area.count()):
  4477. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4478. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4479. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4480. self.tools_db_changed_flag = True
  4481. def on_geometry_tool_add_from_db_executed(self, tool):
  4482. """
  4483. Here add the tool from DB in the selected geometry object.
  4484. :return:
  4485. """
  4486. tool_from_db = deepcopy(tool)
  4487. obj = self.collection.get_active()
  4488. if isinstance(obj, GeometryObject):
  4489. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4490. # close the tab and delete it
  4491. for idx in range(self.ui.plot_tab_area.count()):
  4492. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4493. wdg = self.ui.plot_tab_area.widget(idx)
  4494. wdg.deleteLater()
  4495. self.ui.plot_tab_area.removeTab(idx)
  4496. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4497. else:
  4498. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4499. def on_plot_area_tab_closed(self, tab_obj_name):
  4500. """
  4501. Executed whenever a QTab is closed in the Plot Area.
  4502. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4503. :return:
  4504. """
  4505. if tab_obj_name == "preferences_tab":
  4506. self.preferencesUiManager.on_close_preferences_tab()
  4507. elif tab_obj_name == "database_tab":
  4508. # disconnect the signals from the table widget in tab
  4509. self.tools_db_tab.ui_disconnect()
  4510. if self.tools_db_changed_flag is True:
  4511. msgbox = QtWidgets.QMessageBox()
  4512. msgbox.setText(_("One or more Tools are edited.\n"
  4513. "Do you want to update the Tools Database?"))
  4514. msgbox.setWindowTitle(_("Save Tools Database"))
  4515. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4516. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4517. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4518. msgbox.setDefaultButton(bt_yes)
  4519. msgbox.exec_()
  4520. response = msgbox.clickedButton()
  4521. if response == bt_yes:
  4522. self.tools_db_tab.on_save_tools_db()
  4523. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4524. else:
  4525. self.tools_db_changed_flag = False
  4526. self.inform.emit('')
  4527. return
  4528. self.tools_db_tab.deleteLater()
  4529. elif tab_obj_name == "text_editor_tab":
  4530. self.toggle_codeeditor = False
  4531. elif tab_obj_name == "bookmarks_tab":
  4532. self.book_dialog_tab.rebuild_actions()
  4533. self.book_dialog_tab.deleteLater()
  4534. else:
  4535. return
  4536. # def on_plotarea_tab_closed(self, tab_idx):
  4537. # """
  4538. #
  4539. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4540. # :return:
  4541. # """
  4542. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4543. #
  4544. # if widget is not None:
  4545. # widget.deleteLater()
  4546. # self.ui.plot_tab_area.removeTab(tab_idx)
  4547. def on_flipy(self):
  4548. """
  4549. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4550. :return:
  4551. """
  4552. self.defaults.report_usage("on_flipy()")
  4553. obj_list = self.collection.get_selected()
  4554. xminlist = []
  4555. yminlist = []
  4556. xmaxlist = []
  4557. ymaxlist = []
  4558. if not obj_list:
  4559. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4560. else:
  4561. try:
  4562. # first get a bounding box to fit all
  4563. for obj in obj_list:
  4564. xmin, ymin, xmax, ymax = obj.bounds()
  4565. xminlist.append(xmin)
  4566. yminlist.append(ymin)
  4567. xmaxlist.append(xmax)
  4568. ymaxlist.append(ymax)
  4569. # get the minimum x,y and maximum x,y for all objects selected
  4570. xminimal = min(xminlist)
  4571. yminimal = min(yminlist)
  4572. xmaximal = max(xmaxlist)
  4573. ymaximal = max(ymaxlist)
  4574. px = 0.5 * (xminimal + xmaximal)
  4575. py = 0.5 * (yminimal + ymaximal)
  4576. # execute mirroring
  4577. for obj in obj_list:
  4578. obj.mirror('X', [px, py])
  4579. obj.plot()
  4580. self.app_obj.object_changed.emit(obj)
  4581. self.inform.emit('[success] %s' %
  4582. _("Flip on Y axis done."))
  4583. except Exception as e:
  4584. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4585. return
  4586. def on_flipx(self):
  4587. """
  4588. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4589. :return:
  4590. """
  4591. self.defaults.report_usage("on_flipx()")
  4592. obj_list = self.collection.get_selected()
  4593. xminlist = []
  4594. yminlist = []
  4595. xmaxlist = []
  4596. ymaxlist = []
  4597. if not obj_list:
  4598. self.inform.emit('[WARNING_NOTCL] %s' %
  4599. _("No object selected to Flip on X axis."))
  4600. else:
  4601. try:
  4602. # first get a bounding box to fit all
  4603. for obj in obj_list:
  4604. xmin, ymin, xmax, ymax = obj.bounds()
  4605. xminlist.append(xmin)
  4606. yminlist.append(ymin)
  4607. xmaxlist.append(xmax)
  4608. ymaxlist.append(ymax)
  4609. # get the minimum x,y and maximum x,y for all objects selected
  4610. xminimal = min(xminlist)
  4611. yminimal = min(yminlist)
  4612. xmaximal = max(xmaxlist)
  4613. ymaximal = max(ymaxlist)
  4614. px = 0.5 * (xminimal + xmaximal)
  4615. py = 0.5 * (yminimal + ymaximal)
  4616. # execute mirroring
  4617. for obj in obj_list:
  4618. obj.mirror('Y', [px, py])
  4619. obj.plot()
  4620. self.app_obj.object_changed.emit(obj)
  4621. self.inform.emit('[success] %s' %
  4622. _("Flip on X axis done."))
  4623. except Exception as e:
  4624. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4625. return
  4626. def on_rotate(self, silent=False, preset=None):
  4627. """
  4628. Executed when Options -> Rotate Selection menu entry is clicked.
  4629. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4630. :param preset: A value to be used as predefined angle for rotation.
  4631. :return:
  4632. """
  4633. self.defaults.report_usage("on_rotate()")
  4634. obj_list = self.collection.get_selected()
  4635. xminlist = []
  4636. yminlist = []
  4637. xmaxlist = []
  4638. ymaxlist = []
  4639. if not obj_list:
  4640. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4641. else:
  4642. if silent is False:
  4643. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4644. min=-360, max=360, decimals=4,
  4645. init_val=float(self.defaults['tools_transform_rotate']))
  4646. num, ok = rotatebox.get_value()
  4647. else:
  4648. num = preset
  4649. ok = True
  4650. if ok:
  4651. try:
  4652. # first get a bounding box to fit all
  4653. for obj in obj_list:
  4654. xmin, ymin, xmax, ymax = obj.bounds()
  4655. xminlist.append(xmin)
  4656. yminlist.append(ymin)
  4657. xmaxlist.append(xmax)
  4658. ymaxlist.append(ymax)
  4659. # get the minimum x,y and maximum x,y for all objects selected
  4660. xminimal = min(xminlist)
  4661. yminimal = min(yminlist)
  4662. xmaximal = max(xmaxlist)
  4663. ymaximal = max(ymaxlist)
  4664. px = 0.5 * (xminimal + xmaximal)
  4665. py = 0.5 * (yminimal + ymaximal)
  4666. for sel_obj in obj_list:
  4667. sel_obj.rotate(-float(num), point=(px, py))
  4668. sel_obj.plot()
  4669. self.app_obj.object_changed.emit(sel_obj)
  4670. self.inform.emit('[success] %s' % _("Rotation done."))
  4671. except Exception as e:
  4672. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4673. return
  4674. def on_skewx(self):
  4675. """
  4676. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4677. :return:
  4678. """
  4679. self.defaults.report_usage("on_skewx()")
  4680. obj_list = self.collection.get_selected()
  4681. xminlist = []
  4682. yminlist = []
  4683. if not obj_list:
  4684. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4685. else:
  4686. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4687. min=-360, max=360, decimals=4,
  4688. init_val=float(self.defaults['tools_transform_skew_x']))
  4689. num, ok = skewxbox.get_value()
  4690. if ok:
  4691. # first get a bounding box to fit all
  4692. for obj in obj_list:
  4693. xmin, ymin, xmax, ymax = obj.bounds()
  4694. xminlist.append(xmin)
  4695. yminlist.append(ymin)
  4696. # get the minimum x,y and maximum x,y for all objects selected
  4697. xminimal = min(xminlist)
  4698. yminimal = min(yminlist)
  4699. for obj in obj_list:
  4700. obj.skew(num, 0, point=(xminimal, yminimal))
  4701. obj.plot()
  4702. self.app_obj.object_changed.emit(obj)
  4703. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4704. def on_skewy(self):
  4705. """
  4706. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4707. :return:
  4708. """
  4709. self.defaults.report_usage("on_skewy()")
  4710. obj_list = self.collection.get_selected()
  4711. xminlist = []
  4712. yminlist = []
  4713. if not obj_list:
  4714. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4715. else:
  4716. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4717. min=-360, max=360, decimals=4,
  4718. init_val=float(self.defaults['tools_transform_skew_y']))
  4719. num, ok = skewybox.get_value()
  4720. if ok:
  4721. # first get a bounding box to fit all
  4722. for obj in obj_list:
  4723. xmin, ymin, xmax, ymax = obj.bounds()
  4724. xminlist.append(xmin)
  4725. yminlist.append(ymin)
  4726. # get the minimum x,y and maximum x,y for all objects selected
  4727. xminimal = min(xminlist)
  4728. yminimal = min(yminlist)
  4729. for obj in obj_list:
  4730. obj.skew(0, num, point=(xminimal, yminimal))
  4731. obj.plot()
  4732. self.app_obj.object_changed.emit(obj)
  4733. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4734. def on_plots_updated(self):
  4735. """
  4736. Callback used to report when the plots have changed.
  4737. Adjust axes and zooms to fit.
  4738. :return: None
  4739. """
  4740. if self.is_legacy is False:
  4741. self.plotcanvas.update()
  4742. else:
  4743. self.plotcanvas.auto_adjust_axes()
  4744. self.on_zoom_fit()
  4745. self.collection.update_view()
  4746. # self.inform.emit(_("Plots updated ..."))
  4747. def on_toolbar_replot(self):
  4748. """
  4749. Callback for toolbar button. Re-plots all objects.
  4750. :return: None
  4751. """
  4752. self.defaults.report_usage("on_toolbar_replot")
  4753. self.log.debug("on_toolbar_replot()")
  4754. try:
  4755. self.collection.get_active().read_form()
  4756. except AttributeError:
  4757. self.log.debug("on_toolbar_replot(): AttributeError")
  4758. pass
  4759. self.plot_all()
  4760. def grid_status(self):
  4761. return True if self.ui.grid_snap_btn.isChecked() else False
  4762. def populate_cmenu_grids(self):
  4763. units = self.defaults['units'].lower()
  4764. # for act in self.ui.cmenu_gridmenu.actions():
  4765. # act.triggered.disconnect()
  4766. self.ui.cmenu_gridmenu.clear()
  4767. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4768. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4769. _("Grid On/Off"))
  4770. grid_toggle.setCheckable(True)
  4771. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4772. self.ui.cmenu_gridmenu.addSeparator()
  4773. for grid in sorted_list:
  4774. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4775. "%s" % str(grid))
  4776. action.triggered.connect(self.set_grid)
  4777. self.ui.cmenu_gridmenu.addSeparator()
  4778. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4779. _("Add"))
  4780. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4781. _("Delete"))
  4782. grid_add.triggered.connect(self.on_grid_add)
  4783. grid_delete.triggered.connect(self.on_grid_delete)
  4784. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4785. def set_grid(self):
  4786. menu_action = self.sender()
  4787. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4788. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4789. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4790. def on_grid_add(self):
  4791. # ## Current application units in lower Case
  4792. units = self.defaults['units'].lower()
  4793. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4794. text=_('Enter a Grid Value:'),
  4795. min=0.0000, max=99.9999, decimals=4)
  4796. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4797. val, ok = grid_add_popup.get_value()
  4798. if ok:
  4799. if float(val) == 0:
  4800. self.inform.emit('[WARNING_NOTCL] %s' %
  4801. _("Please enter a grid value with non-zero value, in Float format."))
  4802. return
  4803. else:
  4804. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4805. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4806. self.inform.emit('[success] %s...' % _("New Grid added"))
  4807. else:
  4808. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4809. else:
  4810. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4811. def on_grid_delete(self):
  4812. # ## Current application units in lower Case
  4813. units = self.defaults['units'].lower()
  4814. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4815. text='Enter a Grid Value:',
  4816. min=0.0000, max=99.9999, decimals=4)
  4817. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4818. val, ok = grid_del_popup.get_value()
  4819. if ok:
  4820. if float(val) == 0:
  4821. self.inform.emit('[WARNING_NOTCL] %s' %
  4822. _("Please enter a grid value with non-zero value, in Float format."))
  4823. return
  4824. else:
  4825. try:
  4826. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4827. except ValueError:
  4828. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4829. return
  4830. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4831. else:
  4832. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4833. def on_shortcut_list(self):
  4834. self.defaults.report_usage("on_shortcut_list()")
  4835. # add the tab if it was closed
  4836. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4837. # delete the absolute and relative position and messages in the infobar
  4838. self.ui.position_label.setText("")
  4839. # self.ui.rel_position_label.setText("")
  4840. # Switch plot_area to preferences page
  4841. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4842. # self.ui.show()
  4843. def on_select_tab(self, name):
  4844. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4845. if self.ui.splitter.sizes()[0] == 0:
  4846. self.ui.splitter.setSizes([1, 1])
  4847. else:
  4848. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4849. self.ui.splitter.setSizes([0, 1])
  4850. if name == 'project':
  4851. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4852. elif name == 'selected':
  4853. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4854. elif name == 'tool':
  4855. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4856. def on_copy_name(self):
  4857. self.defaults.report_usage("on_copy_name()")
  4858. obj = self.collection.get_active()
  4859. try:
  4860. name = obj.options["name"]
  4861. except AttributeError:
  4862. log.debug("on_copy_name() --> No object selected to copy it's name")
  4863. self.inform.emit('[WARNING_NOTCL]%s' %
  4864. _(" No object selected to copy it's name"))
  4865. return
  4866. self.clipboard.setText(name)
  4867. self.inform.emit(_("Name copied on clipboard ..."))
  4868. def on_mouse_click_over_plot(self, event):
  4869. """
  4870. Default actions are:
  4871. :param event: Contains information about the event, like which button
  4872. was clicked, the pixel coordinates and the axes coordinates.
  4873. :return: None
  4874. """
  4875. self.pos = []
  4876. if self.is_legacy is False:
  4877. event_pos = event.pos
  4878. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4879. # # Set the mouse button for panning
  4880. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4881. else:
  4882. event_pos = (event.xdata, event.ydata)
  4883. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4884. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4885. # So it can receive key presses
  4886. self.plotcanvas.native.setFocus()
  4887. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4888. if self.grid_status():
  4889. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4890. else:
  4891. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4892. try:
  4893. if event.button == 1:
  4894. # Reset here the relative coordinates so there is a new reference on the click position
  4895. if self.rel_point1 is None:
  4896. self.rel_point1 = self.pos
  4897. else:
  4898. self.rel_point2 = copy(self.rel_point1)
  4899. self.rel_point1 = self.pos
  4900. self.on_mouse_move_over_plot(event, origin_click=True)
  4901. except Exception as e:
  4902. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4903. def on_mouse_double_click_over_plot(self, event):
  4904. if event.button == 1:
  4905. self.doubleclick = True
  4906. def on_mouse_move_over_plot(self, event, origin_click=None):
  4907. """
  4908. Callback for the mouse motion event over the plot.
  4909. :param event: Contains information about the event.
  4910. :param origin_click
  4911. :return: None
  4912. """
  4913. if self.is_legacy is False:
  4914. event_pos = event.pos
  4915. if self.defaults["global_pan_button"] == '2':
  4916. pan_button = 2
  4917. else:
  4918. pan_button = 3
  4919. self.event_is_dragging = event.is_dragging
  4920. else:
  4921. event_pos = (event.xdata, event.ydata)
  4922. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4923. if self.defaults["global_pan_button"] == '2':
  4924. pan_button = 3
  4925. else:
  4926. pan_button = 2
  4927. self.event_is_dragging = self.plotcanvas.is_dragging
  4928. # So it can receive key presses but not when the Tcl Shell is active
  4929. if not self.ui.shell_dock.isVisible():
  4930. if not self.plotcanvas.native.hasFocus():
  4931. self.plotcanvas.native.setFocus()
  4932. self.pos_jump = event_pos
  4933. self.ui.popMenu.mouse_is_panning = False
  4934. if origin_click is None:
  4935. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4936. if event.button == pan_button and self.event_is_dragging == 1:
  4937. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4938. if self.ui.popMenu.popup_active:
  4939. self.ui.popMenu.popup_active = False
  4940. return
  4941. self.ui.popMenu.mouse_is_panning = True
  4942. return
  4943. if self.rel_point1 is not None:
  4944. try: # May fail in case mouse not within axes
  4945. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4946. if pos_canvas[0] is None or pos_canvas[1] is None:
  4947. return
  4948. if self.grid_status():
  4949. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4950. # Update cursor
  4951. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4952. symbol='++', edge_color=self.cursor_color_3D,
  4953. edge_width=self.defaults["global_cursor_width"],
  4954. size=self.defaults["global_cursor_size"])
  4955. else:
  4956. pos = (pos_canvas[0], pos_canvas[1])
  4957. self.dx = pos[0] - float(self.rel_point1[0])
  4958. self.dy = pos[1] - float(self.rel_point1[1])
  4959. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4960. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4961. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4962. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4963. units = self.defaults["units"].lower()
  4964. self.plotcanvas.text_hud.text = \
  4965. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4966. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4967. self.mouse = [pos[0], pos[1]]
  4968. # if the mouse is moved and the LMB is clicked then the action is a selection
  4969. if self.event_is_dragging == 1 and event.button == 1:
  4970. self.delete_selection_shape()
  4971. if self.dx < 0:
  4972. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4973. face_color=self.defaults['global_alt_sel_fill'])
  4974. self.selection_type = False
  4975. elif self.dx >= 0:
  4976. self.draw_moving_selection_shape(self.pos, pos)
  4977. self.selection_type = True
  4978. else:
  4979. self.selection_type = None
  4980. else:
  4981. self.selection_type = None
  4982. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4983. if self.defaults['global_hover']:
  4984. for obj in self.collection.get_list():
  4985. try:
  4986. # select the object(s) only if it is enabled (plotted)
  4987. if obj.options['plot']:
  4988. if obj not in self.collection.get_selected():
  4989. poly_obj = Polygon(
  4990. [(obj.options['xmin'], obj.options['ymin']),
  4991. (obj.options['xmax'], obj.options['ymin']),
  4992. (obj.options['xmax'], obj.options['ymax']),
  4993. (obj.options['xmin'], obj.options['ymax'])]
  4994. )
  4995. if Point(pos).within(poly_obj):
  4996. if obj.isHovering is False:
  4997. obj.isHovering = True
  4998. obj.notHovering = True
  4999. # create the selection box around the selected object
  5000. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5001. else:
  5002. if obj.notHovering is True:
  5003. obj.notHovering = False
  5004. obj.isHovering = False
  5005. self.delete_hover_shape()
  5006. except Exception:
  5007. # the Exception here will happen if we try to select on screen and we have an
  5008. # newly (and empty) just created Geometry or Excellon object that do not have the
  5009. # xmin, xmax, ymin, ymax options.
  5010. # In this case poly_obj creation (see above) will fail
  5011. pass
  5012. except Exception as e:
  5013. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5014. self.ui.position_label.setText("")
  5015. # self.ui.rel_position_label.setText("")
  5016. self.mouse = None
  5017. def on_mouse_click_release_over_plot(self, event):
  5018. """
  5019. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5020. and has been registered in ''self.__init__()''.
  5021. :param event: contains information about the event.
  5022. :return:
  5023. """
  5024. if self.is_legacy is False:
  5025. event_pos = event.pos
  5026. right_button = 2
  5027. else:
  5028. event_pos = (event.xdata, event.ydata)
  5029. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5030. right_button = 3
  5031. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5032. if self.grid_status():
  5033. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5034. else:
  5035. pos = (pos_canvas[0], pos_canvas[1])
  5036. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5037. # canvas menu
  5038. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5039. self.ui.popMenu.mouse_is_panning = False
  5040. self.cursor = QtGui.QCursor()
  5041. self.populate_cmenu_grids()
  5042. self.ui.popMenu.popup(self.cursor.pos())
  5043. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5044. # selection and then select a type of selection ("enclosing" or "touching")
  5045. if event.button == 1: # left click
  5046. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5047. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5048. if modifiers == QtCore.Qt.ShiftModifier:
  5049. # do not auto open the Project Tab
  5050. self.click_noproject = True
  5051. self.clipboard.setText(
  5052. self.defaults["global_point_clipboard_format"] %
  5053. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5054. )
  5055. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5056. return
  5057. if self.doubleclick is True:
  5058. self.doubleclick = False
  5059. if self.collection.get_selected():
  5060. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5061. if self.ui.splitter.sizes()[0] == 0:
  5062. self.ui.splitter.setSizes([1, 1])
  5063. try:
  5064. # delete the selection shape(S) as it may be in the way
  5065. self.delete_selection_shape()
  5066. self.delete_hover_shape()
  5067. except Exception as e:
  5068. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5069. return
  5070. else:
  5071. # WORKAROUND for LEGACY MODE
  5072. if self.is_legacy is True:
  5073. # if there is no move on canvas then we have no dragging selection
  5074. if self.dx == 0 or self.dy == 0:
  5075. self.selection_type = None
  5076. if self.selection_type is not None:
  5077. try:
  5078. self.selection_area_handler(self.pos, pos, self.selection_type)
  5079. self.selection_type = None
  5080. except Exception as e:
  5081. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5082. return
  5083. else:
  5084. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5085. if key_modifier == QtCore.Qt.ShiftModifier:
  5086. mod_key = 'Shift'
  5087. elif key_modifier == QtCore.Qt.ControlModifier:
  5088. mod_key = 'Control'
  5089. else:
  5090. mod_key = None
  5091. try:
  5092. if self.command_active is None:
  5093. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5094. # deselect, and if it's not selected then it will be selected
  5095. # If there is no active command (self.command_active is None) then we check if we clicked
  5096. # on a object by checking the bounding limits against mouse click position
  5097. if mod_key == self.defaults["global_mselect_key"]:
  5098. self.select_objects(key='multisel')
  5099. else:
  5100. # If there is no active command (self.command_active is None) then we check if
  5101. # we clicked on a object by checking the bounding limits against mouse click position
  5102. self.select_objects()
  5103. self.delete_hover_shape()
  5104. except Exception as e:
  5105. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5106. return
  5107. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5108. """
  5109. :param start_pos: mouse position when the selection LMB click was done
  5110. :param end_pos: mouse position when the left mouse button is released
  5111. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5112. :return:
  5113. """
  5114. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5115. # delete previous selection shape
  5116. self.delete_selection_shape()
  5117. # make all objects inactive
  5118. self.collection.set_all_inactive()
  5119. for obj in self.collection.get_list():
  5120. try:
  5121. # select the object(s) only if it is enabled (plotted)
  5122. if obj.options['plot']:
  5123. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5124. (obj.options['xmax'], obj.options['ymin']),
  5125. (obj.options['xmax'], obj.options['ymax']),
  5126. (obj.options['xmin'], obj.options['ymax'])])
  5127. if sel_type is True:
  5128. if poly_obj.within(poly_selection):
  5129. # create the selection box around the selected object
  5130. if self.defaults['global_selection_shape'] is True:
  5131. self.draw_selection_shape(obj)
  5132. self.collection.set_active(obj.options['name'])
  5133. else:
  5134. if poly_selection.intersects(poly_obj):
  5135. # create the selection box around the selected object
  5136. if self.defaults['global_selection_shape'] is True:
  5137. self.draw_selection_shape(obj)
  5138. self.collection.set_active(obj.options['name'])
  5139. obj.selection_shape_drawn = True
  5140. except Exception as e:
  5141. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5142. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5143. # In this case poly_obj creation (see above) will fail
  5144. log.debug("App.selection_area_handler() --> %s" % str(e))
  5145. def select_objects(self, key=None):
  5146. """
  5147. Will select objects clicked on canvas
  5148. :param key: for future use in cumulative selection
  5149. :return:
  5150. """
  5151. # list where we store the overlapped objects under our mouse left click position
  5152. if key is None:
  5153. self.objects_under_the_click_list = []
  5154. # Populate the list with the overlapped objects on the click position
  5155. curr_x, curr_y = self.pos
  5156. for obj in self.all_objects_list:
  5157. # ScriptObject and DocumentObject objects can't be selected
  5158. if obj.kind == 'script' or obj.kind == 'document':
  5159. continue
  5160. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5161. continue
  5162. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5163. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5164. if obj.options['name'] not in self.objects_under_the_click_list:
  5165. if obj.options['plot']:
  5166. # add objects to the objects_under_the_click list only if the object is plotted
  5167. # (active and not disabled)
  5168. self.objects_under_the_click_list.append(obj.options['name'])
  5169. try:
  5170. if self.objects_under_the_click_list:
  5171. curr_sel_obj = self.collection.get_active()
  5172. # case when there is only an object under the click and we toggle it
  5173. if len(self.objects_under_the_click_list) == 1:
  5174. if curr_sel_obj is None:
  5175. self.collection.set_active(self.objects_under_the_click_list[0])
  5176. curr_sel_obj = self.collection.get_active()
  5177. # create the selection box around the selected object
  5178. if self.defaults['global_selection_shape'] is True:
  5179. self.draw_selection_shape(curr_sel_obj)
  5180. curr_sel_obj.selection_shape_drawn = True
  5181. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5182. self.collection.on_objects_selection(False)
  5183. self.delete_selection_shape()
  5184. curr_sel_obj.selection_shape_drawn = False
  5185. self.collection.set_active(self.objects_under_the_click_list[0])
  5186. curr_sel_obj = self.collection.get_active()
  5187. # create the selection box around the selected object
  5188. if self.defaults['global_selection_shape'] is True:
  5189. self.draw_selection_shape(curr_sel_obj)
  5190. curr_sel_obj.selection_shape_drawn = True
  5191. self.selected_message(curr_sel_obj=curr_sel_obj)
  5192. elif curr_sel_obj.selection_shape_drawn is False:
  5193. if self.defaults['global_selection_shape'] is True:
  5194. self.draw_selection_shape(curr_sel_obj)
  5195. curr_sel_obj.selection_shape_drawn = True
  5196. else:
  5197. self.collection.on_objects_selection(False)
  5198. self.delete_selection_shape()
  5199. if self.call_source != 'app':
  5200. self.call_source = 'app'
  5201. self.selected_message(curr_sel_obj=curr_sel_obj)
  5202. else:
  5203. # If there is no selected object
  5204. # make active the first element of the overlapped objects list
  5205. if self.collection.get_active() is None:
  5206. self.collection.set_active(self.objects_under_the_click_list[0])
  5207. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5208. name_sel_obj = self.collection.get_active().options['name']
  5209. # In case that there is a selected object but it is not in the overlapped object list
  5210. # make that object inactive and activate the first element in the overlapped object list
  5211. if name_sel_obj not in self.objects_under_the_click_list:
  5212. self.collection.set_inactive(name_sel_obj)
  5213. name_sel_obj = self.objects_under_the_click_list[0]
  5214. self.collection.set_active(name_sel_obj)
  5215. else:
  5216. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5217. self.collection.set_all_inactive()
  5218. self.collection.set_active(
  5219. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5220. curr_sel_obj = self.collection.get_active()
  5221. # delete the possible selection box around a possible selected object
  5222. self.delete_selection_shape()
  5223. curr_sel_obj.selection_shape_drawn = False
  5224. # create the selection box around the selected object
  5225. if self.defaults['global_selection_shape'] is True:
  5226. self.draw_selection_shape(curr_sel_obj)
  5227. curr_sel_obj.selection_shape_drawn = True
  5228. self.selected_message(curr_sel_obj=curr_sel_obj)
  5229. else:
  5230. # deselect everything
  5231. self.collection.on_objects_selection(False)
  5232. # delete the possible selection box around a possible selected object
  5233. self.delete_selection_shape()
  5234. for o in self.collection.get_list():
  5235. o.selection_shape_drawn = False
  5236. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5237. # only when working on App
  5238. if self.call_source == 'app':
  5239. if self.click_noproject is False:
  5240. # if the Tool Tab is in focus don't change focus to Project Tab
  5241. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5242. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5243. else:
  5244. # restore auto open the Project Tab
  5245. self.click_noproject = False
  5246. # delete any text in the status bar, implicitly the last object name that was selected
  5247. # self.inform.emit("")
  5248. else:
  5249. self.call_source = 'app'
  5250. except Exception as e:
  5251. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5252. def selected_message(self, curr_sel_obj):
  5253. if curr_sel_obj:
  5254. if curr_sel_obj.kind == 'gerber':
  5255. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5256. color='green',
  5257. name=str(curr_sel_obj.options['name']),
  5258. tx=_("selected"))
  5259. )
  5260. elif curr_sel_obj.kind == 'excellon':
  5261. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5262. color='brown',
  5263. name=str(curr_sel_obj.options['name']),
  5264. tx=_("selected"))
  5265. )
  5266. elif curr_sel_obj.kind == 'cncjob':
  5267. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5268. color='blue',
  5269. name=str(curr_sel_obj.options['name']),
  5270. tx=_("selected"))
  5271. )
  5272. elif curr_sel_obj.kind == 'geometry':
  5273. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5274. color='red',
  5275. name=str(curr_sel_obj.options['name']),
  5276. tx=_("selected"))
  5277. )
  5278. def delete_hover_shape(self):
  5279. self.hover_shapes.clear()
  5280. self.hover_shapes.redraw()
  5281. def draw_hover_shape(self, sel_obj, color=None):
  5282. """
  5283. :param sel_obj: The object for which the hover shape must be drawn
  5284. :param color: The color of the hover shape
  5285. :return: None
  5286. """
  5287. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5288. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5289. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5290. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5291. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5292. if self.defaults['units'].upper() == 'MM':
  5293. hover_rect = hover_rect.buffer(-0.1)
  5294. hover_rect = hover_rect.buffer(0.2)
  5295. else:
  5296. hover_rect = hover_rect.buffer(-0.00393)
  5297. hover_rect = hover_rect.buffer(0.00787)
  5298. # if color:
  5299. # face = Color(color)
  5300. # face.alpha = 0.2
  5301. # outline = Color(color, alpha=0.8)
  5302. # else:
  5303. # face = Color(self.defaults['global_sel_fill'])
  5304. # face.alpha = 0.2
  5305. # outline = self.defaults['global_sel_line']
  5306. if color:
  5307. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5308. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5309. else:
  5310. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5311. outline = self.defaults['global_sel_line']
  5312. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5313. if self.is_legacy is True:
  5314. self.hover_shapes.redraw()
  5315. def delete_selection_shape(self):
  5316. self.move_tool.sel_shapes.clear()
  5317. self.move_tool.sel_shapes.redraw()
  5318. def draw_selection_shape(self, sel_obj, color=None):
  5319. """
  5320. Will draw a selection shape around the selected object.
  5321. :param sel_obj: The object for which the selection shape must be drawn
  5322. :param color: The color for the selection shape.
  5323. :return: None
  5324. """
  5325. if sel_obj is None:
  5326. return
  5327. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5328. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5329. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5330. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5331. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5332. if self.defaults['units'].upper() == 'MM':
  5333. sel_rect = sel_rect.buffer(-0.1)
  5334. sel_rect = sel_rect.buffer(0.2)
  5335. else:
  5336. sel_rect = sel_rect.buffer(-0.00393)
  5337. sel_rect = sel_rect.buffer(0.00787)
  5338. if color:
  5339. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5340. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5341. else:
  5342. if self.is_legacy is False:
  5343. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5344. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5345. else:
  5346. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5347. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5348. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5349. color=outline,
  5350. face_color=face,
  5351. update=True,
  5352. layer=0,
  5353. tolerance=None))
  5354. if self.is_legacy is True:
  5355. self.move_tool.sel_shapes.redraw()
  5356. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5357. """
  5358. Will draw a selection shape when dragging mouse on canvas.
  5359. :param old_coords: Old coordinates
  5360. :param coords: New coordinates
  5361. :param kwargs: Keyword arguments
  5362. :return:
  5363. """
  5364. if 'color' in kwargs:
  5365. color = kwargs['color']
  5366. else:
  5367. color = self.defaults['global_sel_line']
  5368. if 'face_color' in kwargs:
  5369. face_color = kwargs['face_color']
  5370. else:
  5371. face_color = self.defaults['global_sel_fill']
  5372. if 'face_alpha' in kwargs:
  5373. face_alpha = kwargs['face_alpha']
  5374. else:
  5375. face_alpha = 0.3
  5376. x0, y0 = old_coords
  5377. x1, y1 = coords
  5378. pt1 = (x0, y0)
  5379. pt2 = (x1, y0)
  5380. pt3 = (x1, y1)
  5381. pt4 = (x0, y1)
  5382. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5383. # color_t = Color(face_color)
  5384. # color_t.alpha = face_alpha
  5385. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5386. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5387. layer=0, tolerance=None)
  5388. if self.is_legacy is True:
  5389. self.move_tool.sel_shapes.redraw()
  5390. def on_file_new_click(self):
  5391. """
  5392. Callback for menu item File -> New.
  5393. Executed on clicking the Menu -> File -> New Project
  5394. :return:
  5395. """
  5396. if self.collection.get_list() and self.should_we_save:
  5397. msgbox = QtWidgets.QMessageBox()
  5398. # msgbox.setText("<B>Save changes ...</B>")
  5399. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5400. "Creating a New project will delete them.\n"
  5401. "Do you want to Save the project?"))
  5402. msgbox.setWindowTitle(_("Save changes"))
  5403. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5404. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5405. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5406. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5407. msgbox.setDefaultButton(bt_yes)
  5408. msgbox.exec_()
  5409. response = msgbox.clickedButton()
  5410. if response == bt_yes:
  5411. self.on_file_saveprojectas()
  5412. elif response == bt_cancel:
  5413. return
  5414. elif response == bt_no:
  5415. self.on_file_new()
  5416. else:
  5417. self.on_file_new()
  5418. self.inform.emit('[success] %s...' % _("New Project created"))
  5419. def on_file_new(self, cli=None):
  5420. """
  5421. Returns the application to its startup state. This method is thread-safe.
  5422. :param cli: Boolean. If True this method was run from command line
  5423. :return: None
  5424. """
  5425. self.defaults.report_usage("on_file_new")
  5426. # Remove everything from memory
  5427. App.log.debug("on_file_new()")
  5428. # close any editor that might be open
  5429. if self.call_source != 'app':
  5430. self.editor2object(cleanup=True)
  5431. # ## EDITOR section
  5432. self.geo_editor = FlatCAMGeoEditor(self)
  5433. self.exc_editor = FlatCAMExcEditor(self)
  5434. self.grb_editor = FlatCAMGrbEditor(self)
  5435. # Clear pool
  5436. self.clear_pool()
  5437. for obj in self.collection.get_list():
  5438. # delete shapes left drawn from mark shape_collections, if any
  5439. if isinstance(obj, GerberObject):
  5440. try:
  5441. for el in obj.mark_shapes:
  5442. obj.mark_shapes[el].clear(update=True)
  5443. obj.mark_shapes[el].enabled = False
  5444. del el
  5445. except AttributeError:
  5446. pass
  5447. # also delete annotation shapes, if any
  5448. elif isinstance(obj, CNCJobObject):
  5449. try:
  5450. obj.text_col.enabled = False
  5451. del obj.text_col
  5452. obj.annotation.clear(update=True)
  5453. del obj.annotation
  5454. except AttributeError:
  5455. pass
  5456. # delete the exclusion areas
  5457. self.exc_areas.clear_shapes()
  5458. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5459. self.shell.init_tcl()
  5460. # delete any selection shape on canvas
  5461. self.delete_selection_shape()
  5462. # delete all FlatCAM objects
  5463. self.collection.delete_all()
  5464. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5465. self.setup_component_editor()
  5466. # Clear project filename
  5467. self.project_filename = None
  5468. # Load the application defaults
  5469. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5470. # Re-fresh project options
  5471. self.on_options_app2project()
  5472. # Init FlatCAMTools
  5473. self.init_tools()
  5474. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5475. if cli is None:
  5476. # we need to go in reverse because once we remove a tab then the index changes
  5477. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5478. # and so on. Therefore the deletion should be done in reverse
  5479. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5480. for index in range(wdg_count, -1, -1):
  5481. try:
  5482. self.ui.plot_tab_area.closeTab(index)
  5483. except Exception as e:
  5484. log.debug("App.on_file_new() --> %s" % str(e))
  5485. # # And then add again the Plot Area
  5486. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5487. self.ui.plot_tab_area.protectTab(0)
  5488. # take the focus of the Notebook on Project Tab.
  5489. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5490. self.set_ui_title(name=_("New Project - Not saved"))
  5491. def obj_properties(self):
  5492. """
  5493. Will launch the object Properties Tool
  5494. :return:
  5495. """
  5496. self.defaults.report_usage("obj_properties()")
  5497. self.properties_tool.run(toggle=False)
  5498. def on_project_context_save(self):
  5499. """
  5500. Wrapper, will save the object function of it's type
  5501. :return:
  5502. """
  5503. obj = self.collection.get_active()
  5504. if type(obj) == GeometryObject:
  5505. self.on_file_exportdxf()
  5506. elif type(obj) == ExcellonObject:
  5507. self.on_file_saveexcellon()
  5508. elif type(obj) == CNCJobObject:
  5509. obj.on_exportgcode_button_click()
  5510. elif type(obj) == GerberObject:
  5511. self.on_file_savegerber()
  5512. elif type(obj) == ScriptObject:
  5513. self.on_file_savescript()
  5514. elif type(obj) == DocumentObject:
  5515. self.on_file_savedocument()
  5516. def obj_move(self):
  5517. """
  5518. Callback for the Move menu entry in various Context Menu's.
  5519. :return:
  5520. """
  5521. self.defaults.report_usage("obj_move()")
  5522. self.move_tool.run(toggle=False)
  5523. def on_fileopengerber(self, signal, name=None):
  5524. """
  5525. File menu callback for opening a Gerber.
  5526. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5527. :param name:
  5528. :return: None
  5529. """
  5530. self.defaults.report_usage("on_fileopengerber")
  5531. App.log.debug("on_fileopengerber()")
  5532. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5533. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5534. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5535. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5536. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5537. "*.mil);;" \
  5538. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5539. "Allegro Files (*.art);;" \
  5540. "Mentor Files (*.pho *.gdo);;" \
  5541. "All Files (*.*)"
  5542. if name is None:
  5543. try:
  5544. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5545. directory=self.get_last_folder(),
  5546. filter=_filter_)
  5547. except TypeError:
  5548. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5549. filenames = [str(filename) for filename in filenames]
  5550. else:
  5551. filenames = [name]
  5552. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5553. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5554. _("Opening Gerber file.")),
  5555. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5556. color=QtGui.QColor("gray"))
  5557. if len(filenames) == 0:
  5558. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5559. else:
  5560. for filename in filenames:
  5561. if filename != '':
  5562. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5563. def on_fileopenexcellon(self, signal, name=None):
  5564. """
  5565. File menu callback for opening an Excellon file.
  5566. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5567. :param name:
  5568. :return: None
  5569. """
  5570. self.defaults.report_usage("on_fileopenexcellon")
  5571. App.log.debug("on_fileopenexcellon()")
  5572. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5573. "All Files (*.*)"
  5574. if name is None:
  5575. try:
  5576. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5577. directory=self.get_last_folder(),
  5578. filter=_filter_)
  5579. except TypeError:
  5580. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5581. filenames = [str(filename) for filename in filenames]
  5582. else:
  5583. filenames = [str(name)]
  5584. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5585. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5586. _("Opening Excellon file.")),
  5587. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5588. color=QtGui.QColor("gray"))
  5589. if len(filenames) == 0:
  5590. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5591. else:
  5592. for filename in filenames:
  5593. if filename != '':
  5594. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5595. def on_fileopengcode(self, signal, name=None):
  5596. """
  5597. File menu call back for opening gcode.
  5598. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5599. :param name:
  5600. :return:
  5601. """
  5602. self.defaults.report_usage("on_fileopengcode")
  5603. App.log.debug("on_fileopengcode()")
  5604. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5605. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5606. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5607. "All Files (*.*)"
  5608. if name is None:
  5609. try:
  5610. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5611. directory=self.get_last_folder(),
  5612. filter=_filter_)
  5613. except TypeError:
  5614. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5615. filenames = [str(filename) for filename in filenames]
  5616. else:
  5617. filenames = [name]
  5618. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5619. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5620. _("Opening G-Code file.")),
  5621. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5622. color=QtGui.QColor("gray"))
  5623. if len(filenames) == 0:
  5624. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5625. else:
  5626. for filename in filenames:
  5627. if filename != '':
  5628. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5629. def on_file_openproject(self, signal):
  5630. """
  5631. File menu callback for opening a project.
  5632. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5633. :return: None
  5634. """
  5635. self.defaults.report_usage("on_file_openproject")
  5636. App.log.debug("on_file_openproject()")
  5637. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5638. try:
  5639. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5640. directory=self.get_last_folder(), filter=_filter_)
  5641. except TypeError:
  5642. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5643. # The Qt methods above will return a QString which can cause problems later.
  5644. # So far json.dump() will fail to serialize it.
  5645. # TODO: Improve the serialization methods and remove this fix.
  5646. filename = str(filename)
  5647. if filename == "":
  5648. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5649. else:
  5650. # self.worker_task.emit({'fcn': self.open_project,
  5651. # 'params': [filename]})
  5652. # The above was failing because open_project() is not
  5653. # thread safe. The new_project()
  5654. self.open_project(filename)
  5655. def on_fileopenhpgl2(self, signal, name=None):
  5656. """
  5657. File menu callback for opening a HPGL2.
  5658. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5659. :param name:
  5660. :return: None
  5661. """
  5662. self.defaults.report_usage("on_fileopenhpgl2")
  5663. App.log.debug("on_fileopenhpgl2()")
  5664. _filter_ = "HPGL2 Files (*.plt);;" \
  5665. "All Files (*.*)"
  5666. if name is None:
  5667. try:
  5668. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5669. directory=self.get_last_folder(),
  5670. filter=_filter_)
  5671. except TypeError:
  5672. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5673. filenames = [str(filename) for filename in filenames]
  5674. else:
  5675. filenames = [name]
  5676. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5677. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5678. _("Opening HPGL2 file.")),
  5679. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5680. color=QtGui.QColor("gray"))
  5681. if len(filenames) == 0:
  5682. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5683. else:
  5684. for filename in filenames:
  5685. if filename != '':
  5686. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5687. def on_file_openconfig(self, signal):
  5688. """
  5689. File menu callback for opening a config file.
  5690. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5691. :return: None
  5692. """
  5693. self.defaults.report_usage("on_file_openconfig")
  5694. App.log.debug("on_file_openconfig()")
  5695. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5696. try:
  5697. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5698. directory=self.data_path, filter=_filter_)
  5699. except TypeError:
  5700. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5701. filter=_filter_)
  5702. if filename == "":
  5703. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5704. else:
  5705. self.open_config_file(filename)
  5706. def on_file_exportsvg(self):
  5707. """
  5708. Callback for menu item File->Export SVG.
  5709. :return: None
  5710. """
  5711. self.defaults.report_usage("on_file_exportsvg")
  5712. App.log.debug("on_file_exportsvg()")
  5713. obj = self.collection.get_active()
  5714. if obj is None:
  5715. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5716. msg = _("Please Select a Geometry object to export")
  5717. msgbox = QtWidgets.QMessageBox()
  5718. msgbox.setInformativeText(msg)
  5719. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5720. msgbox.setDefaultButton(bt_ok)
  5721. msgbox.exec_()
  5722. return
  5723. # Check for more compatible types and add as required
  5724. if (not isinstance(obj, GeometryObject)
  5725. and not isinstance(obj, GerberObject)
  5726. and not isinstance(obj, CNCJobObject)
  5727. and not isinstance(obj, ExcellonObject)):
  5728. msg = '[ERROR_NOTCL] %s' % \
  5729. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5730. msgbox = QtWidgets.QMessageBox()
  5731. msgbox.setInformativeText(msg)
  5732. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5733. msgbox.setDefaultButton(bt_ok)
  5734. msgbox.exec_()
  5735. return
  5736. name = obj.options["name"]
  5737. _filter = "SVG File (*.svg);;All Files (*.*)"
  5738. try:
  5739. filename, _f = FCFileSaveDialog.get_saved_filename(
  5740. caption=_("Export SVG"),
  5741. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5742. filter=_filter)
  5743. except TypeError:
  5744. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5745. filename = str(filename)
  5746. if filename == "":
  5747. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5748. return
  5749. else:
  5750. self.export_svg(name, filename)
  5751. if self.defaults["global_open_style"] is False:
  5752. self.file_opened.emit("SVG", filename)
  5753. self.file_saved.emit("SVG", filename)
  5754. def on_file_exportpng(self):
  5755. self.defaults.report_usage("on_file_exportpng")
  5756. App.log.debug("on_file_exportpng()")
  5757. self.date = str(datetime.today()).rpartition('.')[0]
  5758. self.date = ''.join(c for c in self.date if c not in ':-')
  5759. self.date = self.date.replace(' ', '_')
  5760. if self.is_legacy is False:
  5761. image = _screenshot()
  5762. data = np.asarray(image)
  5763. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5764. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5765. return
  5766. filter_ = "PNG File (*.png);;All Files (*.*)"
  5767. try:
  5768. filename, _f = FCFileSaveDialog.get_saved_filename(
  5769. caption=_("Export PNG Image"),
  5770. directory=self.get_last_save_folder() + '/png_' + self.date,
  5771. filter=filter_)
  5772. except TypeError:
  5773. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5774. filename = str(filename)
  5775. if filename == "":
  5776. self.inform.emit(_("Cancelled."))
  5777. return
  5778. else:
  5779. if self.is_legacy is False:
  5780. write_png(filename, data)
  5781. else:
  5782. self.plotcanvas.figure.savefig(filename)
  5783. if self.defaults["global_open_style"] is False:
  5784. self.file_opened.emit("png", filename)
  5785. self.file_saved.emit("png", filename)
  5786. def on_file_savegerber(self):
  5787. """
  5788. Callback for menu item in Project context menu.
  5789. :return: None
  5790. """
  5791. self.defaults.report_usage("on_file_savegerber")
  5792. App.log.debug("on_file_savegerber()")
  5793. obj = self.collection.get_active()
  5794. if obj is None:
  5795. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5796. return
  5797. # Check for more compatible types and add as required
  5798. if not isinstance(obj, GerberObject):
  5799. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5800. return
  5801. name = self.collection.get_active().options["name"]
  5802. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5803. try:
  5804. filename, _f = FCFileSaveDialog.get_saved_filename(
  5805. caption="Save Gerber source file",
  5806. directory=self.get_last_save_folder() + '/' + name,
  5807. filter=_filter)
  5808. except TypeError:
  5809. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5810. filename = str(filename)
  5811. if filename == "":
  5812. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5813. return
  5814. else:
  5815. self.save_source_file(name, filename)
  5816. if self.defaults["global_open_style"] is False:
  5817. self.file_opened.emit("Gerber", filename)
  5818. self.file_saved.emit("Gerber", filename)
  5819. def on_file_savescript(self):
  5820. """
  5821. Callback for menu item in Project context menu.
  5822. :return: None
  5823. """
  5824. self.defaults.report_usage("on_file_savescript")
  5825. App.log.debug("on_file_savescript()")
  5826. obj = self.collection.get_active()
  5827. if obj is None:
  5828. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5829. return
  5830. # Check for more compatible types and add as required
  5831. if not isinstance(obj, ScriptObject):
  5832. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5833. return
  5834. name = self.collection.get_active().options["name"]
  5835. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5836. try:
  5837. filename, _f = FCFileSaveDialog.get_saved_filename(
  5838. caption="Save Script source file",
  5839. directory=self.get_last_save_folder() + '/' + name,
  5840. filter=_filter)
  5841. except TypeError:
  5842. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5843. filename = str(filename)
  5844. if filename == "":
  5845. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5846. return
  5847. else:
  5848. self.save_source_file(name, filename)
  5849. if self.defaults["global_open_style"] is False:
  5850. self.file_opened.emit("Script", filename)
  5851. self.file_saved.emit("Script", filename)
  5852. def on_file_savedocument(self):
  5853. """
  5854. Callback for menu item in Project context menu.
  5855. :return: None
  5856. """
  5857. self.defaults.report_usage("on_file_savedocument")
  5858. App.log.debug("on_file_savedocument()")
  5859. obj = self.collection.get_active()
  5860. if obj is None:
  5861. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5862. return
  5863. # Check for more compatible types and add as required
  5864. if not isinstance(obj, ScriptObject):
  5865. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5866. return
  5867. name = self.collection.get_active().options["name"]
  5868. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5869. try:
  5870. filename, _f = FCFileSaveDialog.get_saved_filename(
  5871. caption="Save Document source file",
  5872. directory=self.get_last_save_folder() + '/' + name,
  5873. filter=_filter)
  5874. except TypeError:
  5875. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5876. filename = str(filename)
  5877. if filename == "":
  5878. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5879. return
  5880. else:
  5881. self.save_source_file(name, filename)
  5882. if self.defaults["global_open_style"] is False:
  5883. self.file_opened.emit("Document", filename)
  5884. self.file_saved.emit("Document", filename)
  5885. def on_file_saveexcellon(self):
  5886. """
  5887. Callback for menu item in project context menu.
  5888. :return: None
  5889. """
  5890. self.defaults.report_usage("on_file_saveexcellon")
  5891. App.log.debug("on_file_saveexcellon()")
  5892. obj = self.collection.get_active()
  5893. if obj is None:
  5894. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5895. return
  5896. # Check for more compatible types and add as required
  5897. if not isinstance(obj, ExcellonObject):
  5898. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5899. return
  5900. name = self.collection.get_active().options["name"]
  5901. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5902. try:
  5903. filename, _f = FCFileSaveDialog.get_saved_filename(
  5904. caption=_("Save Excellon source file"),
  5905. directory=self.get_last_save_folder() + '/' + name,
  5906. filter=_filter)
  5907. except TypeError:
  5908. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5909. filename = str(filename)
  5910. if filename == "":
  5911. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5912. return
  5913. else:
  5914. self.save_source_file(name, filename)
  5915. if self.defaults["global_open_style"] is False:
  5916. self.file_opened.emit("Excellon", filename)
  5917. self.file_saved.emit("Excellon", filename)
  5918. def on_file_exportexcellon(self):
  5919. """
  5920. Callback for menu item File->Export->Excellon.
  5921. :return: None
  5922. """
  5923. self.defaults.report_usage("on_file_exportexcellon")
  5924. App.log.debug("on_file_exportexcellon()")
  5925. obj = self.collection.get_active()
  5926. if obj is None:
  5927. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5928. return
  5929. # Check for more compatible types and add as required
  5930. if not isinstance(obj, ExcellonObject):
  5931. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5932. return
  5933. name = self.collection.get_active().options["name"]
  5934. _filter = self.defaults["excellon_save_filters"]
  5935. try:
  5936. filename, _f = FCFileSaveDialog.get_saved_filename(
  5937. caption=_("Export Excellon"),
  5938. directory=self.get_last_save_folder() + '/' + name,
  5939. filter=_filter)
  5940. except TypeError:
  5941. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5942. filename = str(filename)
  5943. if filename == "":
  5944. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5945. return
  5946. else:
  5947. used_extension = filename.rpartition('.')[2]
  5948. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5949. self.export_excellon(name, filename)
  5950. if self.defaults["global_open_style"] is False:
  5951. self.file_opened.emit("Excellon", filename)
  5952. self.file_saved.emit("Excellon", filename)
  5953. def on_file_exportgerber(self):
  5954. """
  5955. Callback for menu item File->Export->Gerber.
  5956. :return: None
  5957. """
  5958. self.defaults.report_usage("on_file_exportgerber")
  5959. App.log.debug("on_file_exportgerber()")
  5960. obj = self.collection.get_active()
  5961. if obj is None:
  5962. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5963. return
  5964. # Check for more compatible types and add as required
  5965. if not isinstance(obj, GerberObject):
  5966. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5967. return
  5968. name = self.collection.get_active().options["name"]
  5969. _filter_ = self.defaults['gerber_save_filters']
  5970. try:
  5971. filename, _f = FCFileSaveDialog.get_saved_filename(
  5972. caption=_("Export Gerber"),
  5973. directory=self.get_last_save_folder() + '/' + name,
  5974. filter=_filter_)
  5975. except TypeError:
  5976. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5977. filename = str(filename)
  5978. if filename == "":
  5979. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5980. return
  5981. else:
  5982. used_extension = filename.rpartition('.')[2]
  5983. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5984. self.export_gerber(name, filename)
  5985. if self.defaults["global_open_style"] is False:
  5986. self.file_opened.emit("Gerber", filename)
  5987. self.file_saved.emit("Gerber", filename)
  5988. def on_file_exportdxf(self):
  5989. """
  5990. Callback for menu item File->Export DXF.
  5991. :return: None
  5992. """
  5993. self.defaults.report_usage("on_file_exportdxf")
  5994. App.log.debug("on_file_exportdxf()")
  5995. obj = self.collection.get_active()
  5996. if obj is None:
  5997. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5998. msg = _("Please Select a Geometry object to export")
  5999. msgbox = QtWidgets.QMessageBox()
  6000. msgbox.setInformativeText(msg)
  6001. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6002. msgbox.setDefaultButton(bt_ok)
  6003. msgbox.exec_()
  6004. return
  6005. # Check for more compatible types and add as required
  6006. if not isinstance(obj, GeometryObject):
  6007. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6008. msgbox = QtWidgets.QMessageBox()
  6009. msgbox.setInformativeText(msg)
  6010. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6011. msgbox.setDefaultButton(bt_ok)
  6012. msgbox.exec_()
  6013. return
  6014. name = self.collection.get_active().options["name"]
  6015. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6016. try:
  6017. filename, _f = FCFileSaveDialog.get_saved_filename(
  6018. caption=_("Export DXF"),
  6019. directory=self.get_last_save_folder() + '/' + name,
  6020. filter=_filter_)
  6021. except TypeError:
  6022. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6023. filename = str(filename)
  6024. if filename == "":
  6025. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6026. return
  6027. else:
  6028. self.export_dxf(name, filename)
  6029. if self.defaults["global_open_style"] is False:
  6030. self.file_opened.emit("DXF", filename)
  6031. self.file_saved.emit("DXF", filename)
  6032. def on_file_importsvg(self, type_of_obj):
  6033. """
  6034. Callback for menu item File->Import SVG.
  6035. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6036. :type type_of_obj: str
  6037. :return: None
  6038. """
  6039. self.defaults.report_usage("on_file_importsvg")
  6040. App.log.debug("on_file_importsvg()")
  6041. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6042. try:
  6043. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6044. directory=self.get_last_folder(), filter=_filter_)
  6045. except TypeError:
  6046. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6047. filter=_filter_)
  6048. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6049. type_of_obj = "geometry"
  6050. filenames = [str(filename) for filename in filenames]
  6051. if len(filenames) == 0:
  6052. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6053. else:
  6054. for filename in filenames:
  6055. if filename != '':
  6056. self.worker_task.emit({'fcn': self.import_svg,
  6057. 'params': [filename, type_of_obj]})
  6058. def on_file_importdxf(self, type_of_obj):
  6059. """
  6060. Callback for menu item File->Import DXF.
  6061. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6062. :type type_of_obj: str
  6063. :return: None
  6064. """
  6065. self.defaults.report_usage("on_file_importdxf")
  6066. App.log.debug("on_file_importdxf()")
  6067. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6068. try:
  6069. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6070. directory=self.get_last_folder(),
  6071. filter=_filter_)
  6072. except TypeError:
  6073. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6074. filter=_filter_)
  6075. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6076. type_of_obj = "geometry"
  6077. filenames = [str(filename) for filename in filenames]
  6078. if len(filenames) == 0:
  6079. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6080. else:
  6081. for filename in filenames:
  6082. if filename != '':
  6083. self.worker_task.emit({'fcn': self.import_dxf,
  6084. 'params': [filename, type_of_obj]})
  6085. # ###############################################################################################################
  6086. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6087. # ###############################################################################################################
  6088. def init_code_editor(self, name):
  6089. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6090. # add the tab if it was closed
  6091. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6092. self.text_editor_tab.setObjectName('text_editor_tab')
  6093. # delete the absolute and relative position and messages in the infobar
  6094. self.ui.position_label.setText("")
  6095. # self.ui.rel_position_label.setText("")
  6096. # first clear previous text in text editor (if any)
  6097. self.text_editor_tab.code_editor.clear()
  6098. self.text_editor_tab.code_editor.setReadOnly(False)
  6099. self.toggle_codeeditor = True
  6100. self.text_editor_tab.code_editor.completer_enable = False
  6101. self.text_editor_tab.buttonRun.hide()
  6102. # make sure to keep a reference to the code editor
  6103. self.reference_code_editor = self.text_editor_tab.code_editor
  6104. # Switch plot_area to CNCJob tab
  6105. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6106. def on_view_source(self):
  6107. """
  6108. Called when the user wants to see the source file of the selected object
  6109. :return:
  6110. """
  6111. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6112. self.proc_container.view.set_busy(_("Loading..."))
  6113. try:
  6114. obj = self.collection.get_active()
  6115. except Exception as e:
  6116. log.debug("App.on_view_source() --> %s" % str(e))
  6117. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6118. return 'fail'
  6119. if obj is None:
  6120. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6121. return 'fail'
  6122. flt = "All Files (*.*)"
  6123. if obj.kind == 'gerber':
  6124. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6125. elif obj.kind == 'excellon':
  6126. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6127. elif obj.kind == 'cncjob':
  6128. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6129. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6130. # add the tab if it was closed
  6131. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6132. self.source_editor_tab.setObjectName('source_editor_tab')
  6133. # delete the absolute and relative position and messages in the infobar
  6134. self.ui.position_label.setText("")
  6135. # self.ui.rel_position_label.setText("")
  6136. # first clear previous text in text editor (if any)
  6137. self.source_editor_tab.code_editor.clear()
  6138. self.source_editor_tab.code_editor.setReadOnly(False)
  6139. self.source_editor_tab.code_editor.completer_enable = False
  6140. self.source_editor_tab.buttonRun.hide()
  6141. # Switch plot_area to CNCJob tab
  6142. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6143. try:
  6144. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6145. except TypeError:
  6146. pass
  6147. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6148. try:
  6149. self.source_editor_tab.buttonSave.clicked.disconnect()
  6150. except TypeError:
  6151. pass
  6152. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6153. # then append the text from GCode to the text editor
  6154. if obj.kind == 'cncjob':
  6155. try:
  6156. file = obj.export_gcode(
  6157. preamble=self.defaults["cncjob_prepend"],
  6158. postamble=self.defaults["cncjob_append"],
  6159. to_file=True)
  6160. if file == 'fail':
  6161. return 'fail'
  6162. except AttributeError:
  6163. self.inform.emit('[WARNING_NOTCL] %s' %
  6164. _("There is no selected object for which to see it's source file code."))
  6165. return 'fail'
  6166. else:
  6167. try:
  6168. file = StringIO(obj.source_file)
  6169. except (AttributeError, TypeError):
  6170. self.inform.emit('[WARNING_NOTCL] %s' %
  6171. _("There is no selected object for which to see it's source file code."))
  6172. return 'fail'
  6173. self.source_editor_tab.t_frame.hide()
  6174. try:
  6175. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6176. # for line in file:
  6177. # QtWidgets.QApplication.processEvents()
  6178. # proc_line = str(line).strip('\n')
  6179. # self.source_editor_tab.code_editor.append(proc_line)
  6180. except Exception as e:
  6181. log.debug('App.on_view_source() -->%s' % str(e))
  6182. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6183. return
  6184. self.source_editor_tab.handleTextChanged()
  6185. self.source_editor_tab.t_frame.show()
  6186. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6187. self.proc_container.view.set_idle()
  6188. # self.ui.show()
  6189. def on_toggle_code_editor(self):
  6190. self.defaults.report_usage("on_toggle_code_editor()")
  6191. if self.toggle_codeeditor is False:
  6192. self.init_code_editor(name=_("Code Editor"))
  6193. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6194. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6195. self.text_editor_tab.buttonSave.clicked.disconnect()
  6196. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6197. else:
  6198. for idx in range(self.ui.plot_tab_area.count()):
  6199. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6200. self.ui.plot_tab_area.closeTab(idx)
  6201. break
  6202. self.toggle_codeeditor = False
  6203. def on_code_editor_close(self):
  6204. self.toggle_codeeditor = False
  6205. def goto_text_line(self):
  6206. """
  6207. Will scroll a text to the specified text line.
  6208. :return: None
  6209. """
  6210. dia_box = Dialog_box(title=_("Go to Line ..."),
  6211. label=_("Line:"),
  6212. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6213. initial_text='')
  6214. try:
  6215. line = int(dia_box.location) - 1
  6216. except (ValueError, TypeError):
  6217. line = 0
  6218. if dia_box.ok:
  6219. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6220. # at the top of the window
  6221. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6222. # get the document() of the TextEditor
  6223. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6224. # create a Text Cursor based on the searched line
  6225. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6226. # set cursor of the code editor with the cursor at the searcehd line
  6227. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6228. def on_filenewscript(self, silent=False):
  6229. """
  6230. Will create a new script file and open it in the Code Editor
  6231. :param silent: if True will not display status messages
  6232. :return: None
  6233. """
  6234. if silent is False:
  6235. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6236. # delete the absolute and relative position and messages in the infobar
  6237. self.ui.position_label.setText("")
  6238. # self.ui.rel_position_label.setText("")
  6239. self.app_obj.new_script_object()
  6240. # script_text = script_obj.source_file
  6241. #
  6242. # self.proc_container.view.set_busy(_("Loading..."))
  6243. # script_obj.script_editor_tab.t_frame.hide()
  6244. #
  6245. # script_obj.script_editor_tab.t_frame.show()
  6246. # self.proc_container.view.set_idle()
  6247. def on_fileopenscript(self, name=None, silent=False):
  6248. """
  6249. Will open a Tcl script file into the Code Editor
  6250. :param silent: if True will not display status messages
  6251. :param name: name of a Tcl script file to open
  6252. :return: None
  6253. """
  6254. self.defaults.report_usage("on_fileopenscript")
  6255. App.log.debug("on_fileopenscript()")
  6256. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6257. "All Files (*.*)"
  6258. if name:
  6259. filenames = [name]
  6260. else:
  6261. try:
  6262. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6263. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6264. except TypeError:
  6265. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6266. if len(filenames) == 0:
  6267. if silent is False:
  6268. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6269. else:
  6270. for filename in filenames:
  6271. if filename != '':
  6272. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6273. def on_fileopenscript_example(self, name=None, silent=False):
  6274. """
  6275. Will open a Tcl script file into the Code Editor
  6276. :param silent: if True will not display status messages
  6277. :param name: name of a Tcl script file to open
  6278. :return:
  6279. """
  6280. self.defaults.report_usage("on_fileopenscript_example")
  6281. log.debug("on_fileopenscript_example()")
  6282. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6283. "All Files (*.*)"
  6284. # test if the app was frozen and choose the path for the configuration file
  6285. if getattr(sys, "frozen", False) is True:
  6286. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6287. else:
  6288. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6289. if name:
  6290. filenames = [name]
  6291. else:
  6292. try:
  6293. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6294. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6295. except TypeError:
  6296. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6297. if len(filenames) == 0:
  6298. if silent is False:
  6299. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6300. else:
  6301. for filename in filenames:
  6302. if filename != '':
  6303. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6304. def on_filerunscript(self, name=None, silent=False):
  6305. """
  6306. File menu callback for loading and running a TCL script.
  6307. :param silent: if True will not display status messages
  6308. :param name: name of a Tcl script file to be run by FlatCAM
  6309. :return: None
  6310. """
  6311. self.defaults.report_usage("on_filerunscript")
  6312. App.log.debug("on_file_runscript()")
  6313. if name:
  6314. filename = name
  6315. if self.cmd_line_headless != 1:
  6316. self.splash.showMessage('%s: %ssec\n%s' %
  6317. (_("Canvas initialization started.\n"
  6318. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6319. _("Executing ScriptObject file.")
  6320. ),
  6321. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6322. color=QtGui.QColor("gray"))
  6323. else:
  6324. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6325. "All Files (*.*)"
  6326. try:
  6327. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6328. directory=self.get_last_folder(), filter=_filter_)
  6329. except TypeError:
  6330. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6331. # The Qt methods above will return a QString which can cause problems later.
  6332. # So far json.dump() will fail to serialize it.
  6333. filename = str(filename)
  6334. if filename == "":
  6335. if silent is False:
  6336. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6337. else:
  6338. if self.cmd_line_headless != 1:
  6339. if self.ui.shell_dock.isHidden():
  6340. self.ui.shell_dock.show()
  6341. try:
  6342. with open(filename, "r") as tcl_script:
  6343. cmd_line_shellfile_content = tcl_script.read()
  6344. if self.cmd_line_headless != 1:
  6345. self.shell.exec_command(cmd_line_shellfile_content)
  6346. else:
  6347. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6348. if silent is False:
  6349. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6350. except Exception as e:
  6351. log.debug("App.on_filerunscript() -> %s" % str(e))
  6352. sys.exit(2)
  6353. def on_file_saveproject(self, silent=False):
  6354. """
  6355. Callback for menu item File->Save Project. Saves the project to
  6356. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6357. if set to None. The project is saved by calling ``self.save_project()``.
  6358. :param silent: if True will not display status messages
  6359. :return: None
  6360. """
  6361. self.defaults.report_usage("on_file_saveproject")
  6362. if self.project_filename is None:
  6363. self.on_file_saveprojectas()
  6364. else:
  6365. self.worker_task.emit({'fcn': self.save_project,
  6366. 'params': [self.project_filename, silent]})
  6367. if self.defaults["global_open_style"] is False:
  6368. self.file_opened.emit("project", self.project_filename)
  6369. self.file_saved.emit("project", self.project_filename)
  6370. self.set_ui_title(name=self.project_filename)
  6371. self.should_we_save = False
  6372. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6373. """
  6374. Callback for menu item File->Save Project As... Opens a file
  6375. chooser and saves the project to the given file via
  6376. ``self.save_project()``.
  6377. :param make_copy if to be create a copy of the project; boolean
  6378. :param use_thread: if to be run in a separate thread; boolean
  6379. :param quit_action: if to be followed by quiting the application; boolean
  6380. :return: None
  6381. """
  6382. self.defaults.report_usage("on_file_saveprojectas")
  6383. self.date = str(datetime.today()).rpartition('.')[0]
  6384. self.date = ''.join(c for c in self.date if c not in ':-')
  6385. self.date = self.date.replace(' ', '_')
  6386. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6387. try:
  6388. filename, _f = FCFileSaveDialog.get_saved_filename(
  6389. caption=_("Save Project As ..."),
  6390. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6391. proj=_("Project")),
  6392. filter=filter_
  6393. )
  6394. except TypeError:
  6395. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6396. filename = str(filename)
  6397. if filename == '':
  6398. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6399. return
  6400. if use_thread is True:
  6401. self.worker_task.emit({'fcn': self.save_project,
  6402. 'params': [filename, quit_action]})
  6403. else:
  6404. self.save_project(filename, quit_action)
  6405. # self.save_project(filename)
  6406. if self.defaults["global_open_style"] is False:
  6407. self.file_opened.emit("project", filename)
  6408. self.file_saved.emit("project", filename)
  6409. if not make_copy:
  6410. self.project_filename = filename
  6411. self.set_ui_title(name=self.project_filename)
  6412. self.should_we_save = False
  6413. def on_file_save_objects_pdf(self, use_thread=True):
  6414. self.date = str(datetime.today()).rpartition('.')[0]
  6415. self.date = ''.join(c for c in self.date if c not in ':-')
  6416. self.date = self.date.replace(' ', '_')
  6417. try:
  6418. obj_selection = self.collection.get_selected()
  6419. if len(obj_selection) == 1:
  6420. obj_name = str(obj_selection[0].options['name'])
  6421. else:
  6422. obj_name = _("FlatCAM objects print")
  6423. except AttributeError as err:
  6424. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6425. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6426. return
  6427. if not obj_selection:
  6428. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6429. return
  6430. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6431. try:
  6432. filename, _f = FCFileSaveDialog.get_saved_filename(
  6433. caption=_("Save Object as PDF ..."),
  6434. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6435. obj_name=obj_name,
  6436. date=self.date),
  6437. filter=filter_
  6438. )
  6439. except TypeError:
  6440. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6441. filename = str(filename)
  6442. if filename == '':
  6443. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6444. return
  6445. if use_thread is True:
  6446. self.proc_container.new(_("Printing PDF ... Please wait."))
  6447. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6448. else:
  6449. self.save_pdf(filename, obj_selection)
  6450. # self.save_project(filename)
  6451. if self.defaults["global_open_style"] is False:
  6452. self.file_opened.emit("pdf", filename)
  6453. self.file_saved.emit("pdf", filename)
  6454. def save_pdf(self, file_name, obj_selection):
  6455. p_size = self.defaults['global_workspaceT']
  6456. orientation = self.defaults['global_workspace_orientation']
  6457. color = 'black'
  6458. transparency_level = 1.0
  6459. self.pagesize = {}
  6460. self.pagesize.update(
  6461. {
  6462. 'Bounds': None,
  6463. 'A0': (841 * mm, 1189 * mm),
  6464. 'A1': (594 * mm, 841 * mm),
  6465. 'A2': (420 * mm, 594 * mm),
  6466. 'A3': (297 * mm, 420 * mm),
  6467. 'A4': (210 * mm, 297 * mm),
  6468. 'A5': (148 * mm, 210 * mm),
  6469. 'A6': (105 * mm, 148 * mm),
  6470. 'A7': (74 * mm, 105 * mm),
  6471. 'A8': (52 * mm, 74 * mm),
  6472. 'A9': (37 * mm, 52 * mm),
  6473. 'A10': (26 * mm, 37 * mm),
  6474. 'B0': (1000 * mm, 1414 * mm),
  6475. 'B1': (707 * mm, 1000 * mm),
  6476. 'B2': (500 * mm, 707 * mm),
  6477. 'B3': (353 * mm, 500 * mm),
  6478. 'B4': (250 * mm, 353 * mm),
  6479. 'B5': (176 * mm, 250 * mm),
  6480. 'B6': (125 * mm, 176 * mm),
  6481. 'B7': (88 * mm, 125 * mm),
  6482. 'B8': (62 * mm, 88 * mm),
  6483. 'B9': (44 * mm, 62 * mm),
  6484. 'B10': (31 * mm, 44 * mm),
  6485. 'C0': (917 * mm, 1297 * mm),
  6486. 'C1': (648 * mm, 917 * mm),
  6487. 'C2': (458 * mm, 648 * mm),
  6488. 'C3': (324 * mm, 458 * mm),
  6489. 'C4': (229 * mm, 324 * mm),
  6490. 'C5': (162 * mm, 229 * mm),
  6491. 'C6': (114 * mm, 162 * mm),
  6492. 'C7': (81 * mm, 114 * mm),
  6493. 'C8': (57 * mm, 81 * mm),
  6494. 'C9': (40 * mm, 57 * mm),
  6495. 'C10': (28 * mm, 40 * mm),
  6496. # American paper sizes
  6497. 'LETTER': (8.5 * inch, 11 * inch),
  6498. 'LEGAL': (8.5 * inch, 14 * inch),
  6499. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6500. # From https://en.wikipedia.org/wiki/Paper_size
  6501. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6502. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6503. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6504. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6505. 'LEDGER': (17 * inch, 11 * inch),
  6506. }
  6507. )
  6508. exported_svg = []
  6509. for obj in obj_selection:
  6510. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6511. scale_factor_x=None, scale_factor_y=None,
  6512. skew_factor_x=None, skew_factor_y=None,
  6513. mirror=None)
  6514. if obj.kind.lower() == 'gerber':
  6515. # color = self.defaults["gerber_plot_fill"][:-2]
  6516. color = obj.fill_color[:-2]
  6517. elif obj.kind.lower() == 'excellon':
  6518. color = '#C40000'
  6519. elif obj.kind.lower() == 'geometry':
  6520. color = self.defaults["global_draw_color"]
  6521. # Change the attributes of the exported SVG
  6522. # We don't need stroke-width
  6523. # We set opacity to maximum
  6524. # We set the colour to WHITE
  6525. root = ET.fromstring(svg_obj)
  6526. for child in root:
  6527. child.set('fill', str(color))
  6528. child.set('opacity', str(transparency_level))
  6529. child.set('stroke', str(color))
  6530. exported_svg.append(ET.tostring(root))
  6531. xmin = Inf
  6532. ymin = Inf
  6533. xmax = -Inf
  6534. ymax = -Inf
  6535. for obj in obj_selection:
  6536. try:
  6537. gxmin, gymin, gxmax, gymax = obj.bounds()
  6538. xmin = min([xmin, gxmin])
  6539. ymin = min([ymin, gymin])
  6540. xmax = max([xmax, gxmax])
  6541. ymax = max([ymax, gymax])
  6542. except Exception as e:
  6543. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6544. # Determine bounding area for svg export
  6545. bounds = [xmin, ymin, xmax, ymax]
  6546. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6547. # This contain the measure units
  6548. uom = obj_selection[0].units.lower()
  6549. # Define a boundary around SVG of about 1.0mm (~39mils)
  6550. if uom in "mm":
  6551. boundary = 1.0
  6552. else:
  6553. boundary = 0.0393701
  6554. # Convert everything to strings for use in the xml doc
  6555. svgwidth = str(size[0] + (2 * boundary))
  6556. svgheight = str(size[1] + (2 * boundary))
  6557. minx = str(bounds[0] - boundary)
  6558. miny = str(bounds[1] + boundary + size[1])
  6559. # Add a SVG Header and footer to the svg output from shapely
  6560. # The transform flips the Y Axis so that everything renders
  6561. # properly within svg apps such as inkscape
  6562. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6563. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6564. svg_header += 'width="' + svgwidth + uom + '" '
  6565. svg_header += 'height="' + svgheight + uom + '" '
  6566. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6567. svg_header += '>'
  6568. svg_header += '<g transform="scale(1,-1)">'
  6569. svg_footer = '</g> </svg>'
  6570. svg_elem = str(svg_header)
  6571. for svg_item in exported_svg:
  6572. svg_elem += str(svg_item)
  6573. svg_elem += str(svg_footer)
  6574. # Parse the xml through a xml parser just to add line feeds
  6575. # and to make it look more pretty for the output
  6576. doc = parse_xml_string(svg_elem)
  6577. doc_final = doc.toprettyxml()
  6578. try:
  6579. if self.defaults['units'].upper() == 'IN':
  6580. unit = inch
  6581. else:
  6582. unit = mm
  6583. doc_final = StringIO(doc_final)
  6584. drawing = svg2rlg(doc_final)
  6585. if p_size == 'Bounds':
  6586. renderPDF.drawToFile(drawing, file_name)
  6587. else:
  6588. if orientation == 'p':
  6589. page_size = portrait(self.pagesize[p_size])
  6590. else:
  6591. page_size = landscape(self.pagesize[p_size])
  6592. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6593. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6594. renderPDF.draw(drawing, my_canvas, 0, 0)
  6595. my_canvas.save()
  6596. except Exception as e:
  6597. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6598. return 'fail'
  6599. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6600. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6601. """
  6602. Exports a Geometry Object to an SVG file.
  6603. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6604. :param filename: Path to the SVG file to save to.
  6605. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6606. :return:
  6607. """
  6608. self.defaults.report_usage("export_svg()")
  6609. if filename is None:
  6610. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6611. is not None else self.defaults["global_last_folder"]
  6612. self.log.debug("export_svg()")
  6613. try:
  6614. obj = self.collection.get_by_name(str(obj_name))
  6615. except Exception:
  6616. # TODO: The return behavior has not been established... should raise exception?
  6617. return "Could not retrieve object: %s" % obj_name
  6618. with self.proc_container.new(_("Exporting SVG")) as proc:
  6619. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6620. # Determine bounding area for svg export
  6621. bounds = obj.bounds()
  6622. size = obj.size()
  6623. # Convert everything to strings for use in the xml doc
  6624. svgwidth = str(size[0])
  6625. svgheight = str(size[1])
  6626. minx = str(bounds[0])
  6627. miny = str(bounds[1] - size[1])
  6628. uom = obj.units.lower()
  6629. # Add a SVG Header and footer to the svg output from shapely
  6630. # The transform flips the Y Axis so that everything renders
  6631. # properly within svg apps such as inkscape
  6632. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6633. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6634. svg_header += 'width="' + svgwidth + uom + '" '
  6635. svg_header += 'height="' + svgheight + uom + '" '
  6636. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6637. svg_header += '<g transform="scale(1,-1)">'
  6638. svg_footer = '</g> </svg>'
  6639. svg_elem = svg_header + exported_svg + svg_footer
  6640. # Parse the xml through a xml parser just to add line feeds
  6641. # and to make it look more pretty for the output
  6642. svgcode = parse_xml_string(svg_elem)
  6643. svgcode = svgcode.toprettyxml()
  6644. try:
  6645. with open(filename, 'w') as fp:
  6646. fp.write(svgcode)
  6647. except PermissionError:
  6648. self.inform.emit('[WARNING] %s' %
  6649. _("Permission denied, saving not possible.\n"
  6650. "Most likely another app is holding the file open and not accessible."))
  6651. return 'fail'
  6652. if self.defaults["global_open_style"] is False:
  6653. self.file_opened.emit("SVG", filename)
  6654. self.file_saved.emit("SVG", filename)
  6655. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6656. def save_source_file(self, obj_name, filename, use_thread=True):
  6657. """
  6658. Exports a FlatCAM Object to an Gerber/Excellon file.
  6659. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6660. :param filename: Path to the Gerber file to save to.
  6661. :param use_thread: if to be run in a separate thread
  6662. :return:
  6663. """
  6664. self.defaults.report_usage("save source file()")
  6665. if filename is None:
  6666. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6667. is not None else self.defaults["global_last_folder"]
  6668. self.log.debug("save source file()")
  6669. obj = self.collection.get_by_name(obj_name)
  6670. file_string = StringIO(obj.source_file)
  6671. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6672. if file_string.getvalue() == '':
  6673. self.inform.emit('[ERROR_NOTCL] %s' %
  6674. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6675. return 'fail'
  6676. try:
  6677. with open(filename, 'w') as file:
  6678. file.writelines('G04*\n')
  6679. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6680. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6681. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6682. file.writelines('G04 Created on : %s*\n' % time_string)
  6683. for line in file_string:
  6684. file.writelines(line)
  6685. except PermissionError:
  6686. self.inform.emit('[WARNING] %s' %
  6687. _("Permission denied, saving not possible.\n"
  6688. "Most likely another app is holding the file open and not accessible."))
  6689. return 'fail'
  6690. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6691. """
  6692. Exports a Excellon Object to an Excellon file.
  6693. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6694. :param filename: Path to the Excellon file to save to.
  6695. :param local_use:
  6696. :param use_thread: if to be run in a separate thread
  6697. :return:
  6698. """
  6699. self.defaults.report_usage("export_excellon()")
  6700. if filename is None:
  6701. if self.defaults["global_last_save_folder"]:
  6702. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6703. else:
  6704. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6705. self.log.debug("export_excellon()")
  6706. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6707. self.defaults["excellon_exp_decimals"]
  6708. )
  6709. if local_use is None:
  6710. try:
  6711. obj = self.collection.get_by_name(str(obj_name))
  6712. except Exception:
  6713. return "Could not retrieve object: %s" % obj_name
  6714. else:
  6715. obj = local_use
  6716. if not isinstance(obj, ExcellonObject):
  6717. self.inform.emit('[ERROR_NOTCL] %s' %
  6718. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6719. return
  6720. # updated units
  6721. eunits = self.defaults["excellon_exp_units"]
  6722. ewhole = self.defaults["excellon_exp_integer"]
  6723. efract = self.defaults["excellon_exp_decimals"]
  6724. ezeros = self.defaults["excellon_exp_zeros"]
  6725. eformat = self.defaults["excellon_exp_format"]
  6726. slot_type = self.defaults["excellon_exp_slot_type"]
  6727. fc_units = self.defaults['units'].upper()
  6728. if fc_units == 'MM':
  6729. factor = 1 if eunits == 'METRIC' else 0.03937
  6730. else:
  6731. factor = 25.4 if eunits == 'METRIC' else 1
  6732. def make_excellon():
  6733. try:
  6734. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6735. header = 'M48\n'
  6736. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6737. (str(self.version), str(self.version_date))
  6738. header += ';Filename: %s' % str(obj_name) + '\n'
  6739. header += ';Created on : %s' % time_str + '\n'
  6740. if eformat == 'dec':
  6741. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6742. header += eunits + '\n'
  6743. for tool in obj.tools:
  6744. if eunits == 'METRIC':
  6745. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6746. tool=str(tool),
  6747. dec=2)
  6748. else:
  6749. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6750. tool=str(tool),
  6751. dec=4)
  6752. else:
  6753. if ezeros == 'LZ':
  6754. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6755. form='ndec', e_zeros='LZ', factor=factor,
  6756. slot_type=slot_type)
  6757. header += '%s,%s\n' % (eunits, 'LZ')
  6758. header += format_exc
  6759. for tool in obj.tools:
  6760. if eunits == 'METRIC':
  6761. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6762. tool=str(tool),
  6763. dec=2)
  6764. else:
  6765. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6766. tool=str(tool),
  6767. dec=4)
  6768. else:
  6769. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6770. form='ndec', e_zeros='TZ', factor=factor,
  6771. slot_type=slot_type)
  6772. header += '%s,%s\n' % (eunits, 'TZ')
  6773. header += format_exc
  6774. for tool in obj.tools:
  6775. if eunits == 'METRIC':
  6776. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6777. tool=str(tool),
  6778. dec=2)
  6779. else:
  6780. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6781. tool=str(tool),
  6782. dec=4)
  6783. header += '%\n'
  6784. footer = 'M30\n'
  6785. exported_excellon = header
  6786. exported_excellon += excellon_code
  6787. exported_excellon += footer
  6788. if local_use is None:
  6789. try:
  6790. with open(filename, 'w') as fp:
  6791. fp.write(exported_excellon)
  6792. except PermissionError:
  6793. self.inform.emit('[WARNING] %s' %
  6794. _("Permission denied, saving not possible.\n"
  6795. "Most likely another app is holding the file open and not accessible."))
  6796. return 'fail'
  6797. if self.defaults["global_open_style"] is False:
  6798. self.file_opened.emit("Excellon", filename)
  6799. self.file_saved.emit("Excellon", filename)
  6800. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6801. else:
  6802. return exported_excellon
  6803. except Exception as e:
  6804. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6805. return 'fail'
  6806. if use_thread is True:
  6807. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6808. def job_thread_exc(app_obj):
  6809. ret = make_excellon()
  6810. if ret == 'fail':
  6811. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6812. return
  6813. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6814. else:
  6815. eret = make_excellon()
  6816. if eret == 'fail':
  6817. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6818. return 'fail'
  6819. if local_use is not None:
  6820. return eret
  6821. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6822. """
  6823. Exports a Gerber Object to an Gerber file.
  6824. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6825. :param filename: Path to the Gerber file to save to.
  6826. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6827. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6828. :param use_thread: if to be run in a separate thread
  6829. :return:
  6830. """
  6831. self.defaults.report_usage("export_gerber()")
  6832. if filename is None:
  6833. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6834. is not None else self.defaults["global_last_folder"]
  6835. self.log.debug("export_gerber()")
  6836. if local_use is None:
  6837. try:
  6838. obj = self.collection.get_by_name(str(obj_name))
  6839. except Exception:
  6840. return "Could not retrieve object: %s" % obj_name
  6841. else:
  6842. obj = local_use
  6843. # updated units
  6844. gunits = self.defaults["gerber_exp_units"]
  6845. gwhole = self.defaults["gerber_exp_integer"]
  6846. gfract = self.defaults["gerber_exp_decimals"]
  6847. gzeros = self.defaults["gerber_exp_zeros"]
  6848. fc_units = self.defaults['units'].upper()
  6849. if fc_units == 'MM':
  6850. factor = 1 if gunits == 'MM' else 0.03937
  6851. else:
  6852. factor = 25.4 if gunits == 'MM' else 1
  6853. def make_gerber():
  6854. try:
  6855. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6856. header = 'G04*\n'
  6857. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6858. (str(self.version), str(self.version_date))
  6859. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6860. header += 'G04 Created on : %s*' % time_str + '\n'
  6861. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6862. header += "%MO{units}*%\n".format(units=gunits)
  6863. for apid in obj.apertures:
  6864. if obj.apertures[apid]['type'] == 'C':
  6865. header += "%ADD{apid}{type},{size}*%\n".format(
  6866. apid=str(apid),
  6867. type='C',
  6868. size=(factor * obj.apertures[apid]['size'])
  6869. )
  6870. elif obj.apertures[apid]['type'] == 'R':
  6871. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6872. apid=str(apid),
  6873. type='R',
  6874. width=(factor * obj.apertures[apid]['width']),
  6875. height=(factor * obj.apertures[apid]['height'])
  6876. )
  6877. elif obj.apertures[apid]['type'] == 'O':
  6878. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6879. apid=str(apid),
  6880. type='O',
  6881. width=(factor * obj.apertures[apid]['width']),
  6882. height=(factor * obj.apertures[apid]['height'])
  6883. )
  6884. header += '\n'
  6885. # obsolete units but some software may need it
  6886. if gunits == 'IN':
  6887. header += 'G70*\n'
  6888. else:
  6889. header += 'G71*\n'
  6890. # Absolute Mode
  6891. header += 'G90*\n'
  6892. header += 'G01*\n'
  6893. # positive polarity
  6894. header += '%LPD*%\n'
  6895. footer = 'M02*\n'
  6896. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6897. exported_gerber = header
  6898. exported_gerber += gerber_code
  6899. exported_gerber += footer
  6900. if local_use is None:
  6901. try:
  6902. with open(filename, 'w') as fp:
  6903. fp.write(exported_gerber)
  6904. except PermissionError:
  6905. self.inform.emit('[WARNING] %s' %
  6906. _("Permission denied, saving not possible.\n"
  6907. "Most likely another app is holding the file open and not accessible."))
  6908. return 'fail'
  6909. if self.defaults["global_open_style"] is False:
  6910. self.file_opened.emit("Gerber", filename)
  6911. self.file_saved.emit("Gerber", filename)
  6912. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6913. else:
  6914. return exported_gerber
  6915. except Exception as e:
  6916. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6917. return 'fail'
  6918. if use_thread is True:
  6919. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6920. def job_thread_grb(app_obj):
  6921. ret = make_gerber()
  6922. if ret == 'fail':
  6923. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6924. return
  6925. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6926. else:
  6927. gret = make_gerber()
  6928. if gret == 'fail':
  6929. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6930. return 'fail'
  6931. if local_use is not None:
  6932. return gret
  6933. def export_dxf(self, obj_name, filename, use_thread=True):
  6934. """
  6935. Exports a Geometry Object to an DXF file.
  6936. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6937. :param filename: Path to the DXF file to save to.
  6938. :param use_thread: if to be run in a separate thread
  6939. :return:
  6940. """
  6941. self.defaults.report_usage("export_dxf()")
  6942. if filename is None:
  6943. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6944. is not None else self.defaults["global_last_folder"]
  6945. self.log.debug("export_dxf()")
  6946. try:
  6947. obj = self.collection.get_by_name(str(obj_name))
  6948. except Exception:
  6949. # TODO: The return behavior has not been established... should raise exception?
  6950. return "Could not retrieve object: %s" % obj_name
  6951. def make_dxf():
  6952. try:
  6953. dxf_code = obj.export_dxf()
  6954. dxf_code.saveas(filename)
  6955. if self.defaults["global_open_style"] is False:
  6956. self.file_opened.emit("DXF", filename)
  6957. self.file_saved.emit("DXF", filename)
  6958. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6959. except Exception:
  6960. return 'fail'
  6961. if use_thread is True:
  6962. with self.proc_container.new(_("Exporting DXF")) as proc:
  6963. def job_thread_exc(app_obj):
  6964. ret_dxf_val = make_dxf()
  6965. if ret_dxf_val == 'fail':
  6966. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6967. return
  6968. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6969. else:
  6970. ret = make_dxf()
  6971. if ret == 'fail':
  6972. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6973. return
  6974. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6975. """
  6976. Adds a new Geometry Object to the projects and populates
  6977. it with shapes extracted from the SVG file.
  6978. :param plot: If True then the resulting object will be plotted on canvas
  6979. :param filename: Path to the SVG file.
  6980. :param geo_type: Type of FlatCAM object that will be created from SVG
  6981. :param outname: The name given to the resulting FlatCAM object
  6982. :return:
  6983. """
  6984. self.defaults.report_usage("import_svg()")
  6985. log.debug("App.import_svg()")
  6986. obj_type = ""
  6987. if geo_type is None or geo_type == "geometry":
  6988. obj_type = "geometry"
  6989. elif geo_type == "gerber":
  6990. obj_type = "gerber"
  6991. else:
  6992. self.inform.emit('[ERROR_NOTCL] %s' %
  6993. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6994. return
  6995. units = self.defaults['units'].upper()
  6996. def obj_init(geo_obj, app_obj):
  6997. geo_obj.import_svg(filename, obj_type, units=units)
  6998. geo_obj.multigeo = False
  6999. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7000. with self.proc_container.new(_("Importing SVG")) as proc:
  7001. # Object name
  7002. name = outname or filename.split('/')[-1].split('\\')[-1]
  7003. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7004. if ret == 'fail':
  7005. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7006. return 'fail'
  7007. # Register recent file
  7008. self.file_opened.emit("svg", filename)
  7009. # AppGUI feedback
  7010. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7011. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7012. """
  7013. Adds a new Geometry Object to the projects and populates
  7014. it with shapes extracted from the DXF file.
  7015. :param filename: Path to the DXF file.
  7016. :param geo_type: Type of FlatCAM object that will be created from DXF
  7017. :param outname: Name for the imported Geometry
  7018. :param plot: If True then the resulting object will be plotted on canvas
  7019. :return:
  7020. """
  7021. self.defaults.report_usage("import_dxf()")
  7022. obj_type = ""
  7023. if geo_type is None or geo_type == "geometry":
  7024. obj_type = "geometry"
  7025. elif geo_type == "gerber":
  7026. obj_type = geo_type
  7027. else:
  7028. self.inform.emit('[ERROR_NOTCL] %s' %
  7029. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7030. return
  7031. units = self.defaults['units'].upper()
  7032. def obj_init(geo_obj, app_obj):
  7033. geo_obj.import_dxf(filename, obj_type, units=units)
  7034. geo_obj.multigeo = False
  7035. with self.proc_container.new(_("Importing DXF")):
  7036. # Object name
  7037. name = outname or filename.split('/')[-1].split('\\')[-1]
  7038. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7039. if ret == 'fail':
  7040. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7041. return 'fail'
  7042. # Register recent file
  7043. self.file_opened.emit("dxf", filename)
  7044. # AppGUI feedback
  7045. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7046. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7047. """
  7048. Opens a Gerber file, parses it and creates a new object for
  7049. it in the program. Thread-safe.
  7050. :param outname: Name of the resulting object. None causes the
  7051. name to be that of the file. Str.
  7052. :param filename: Gerber file filename
  7053. :type filename: str
  7054. :param plot: boolean, to plot or not the resulting object
  7055. :param from_tcl: True if run from Tcl Shell
  7056. :return: None
  7057. """
  7058. # How the object should be initialized
  7059. def obj_init(gerber_obj, app_obj):
  7060. assert isinstance(gerber_obj, GerberObject), \
  7061. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7062. # Opening the file happens here
  7063. try:
  7064. gerber_obj.parse_file(filename)
  7065. except IOError:
  7066. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7067. return "fail"
  7068. except ParseError as err:
  7069. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7070. app_obj.log.error(str(err))
  7071. return "fail"
  7072. except Exception as e:
  7073. log.debug("App.open_gerber() --> %s" % str(e))
  7074. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7075. msg += traceback.format_exc()
  7076. app_obj.inform.emit(msg)
  7077. return "fail"
  7078. if gerber_obj.is_empty():
  7079. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7080. _("Object is not Gerber file or empty. Aborting object creation."))
  7081. return "fail"
  7082. App.log.debug("open_gerber()")
  7083. with self.proc_container.new(_("Opening Gerber")):
  7084. # Object name
  7085. name = outname or filename.split('/')[-1].split('\\')[-1]
  7086. # # ## Object creation # ##
  7087. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7088. if ret_val == 'fail':
  7089. if from_tcl:
  7090. filename = self.defaults['global_tcl_path'] + '/' + name
  7091. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7092. if ret_val == 'fail':
  7093. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7094. return 'fail'
  7095. # Register recent file
  7096. self.file_opened.emit("gerber", filename)
  7097. # AppGUI feedback
  7098. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7099. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7100. """
  7101. Opens an Excellon file, parses it and creates a new object for
  7102. it in the program. Thread-safe.
  7103. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7104. :param filename: Excellon file filename
  7105. :type filename: str
  7106. :param plot: boolean, to plot or not the resulting object
  7107. :param from_tcl: True if run from Tcl Shell
  7108. :return: None
  7109. """
  7110. App.log.debug("open_excellon()")
  7111. # How the object should be initialized
  7112. def obj_init(excellon_obj, app_obj):
  7113. try:
  7114. ret = excellon_obj.parse_file(filename=filename)
  7115. if ret == "fail":
  7116. log.debug("Excellon parsing failed.")
  7117. self.inform.emit('[ERROR_NOTCL] %s' %
  7118. _("This is not Excellon file."))
  7119. return "fail"
  7120. except IOError:
  7121. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7122. (_("Cannot open file"), filename))
  7123. log.debug("Could not open Excellon object.")
  7124. return "fail"
  7125. except Exception:
  7126. msg = '[ERROR_NOTCL] %s' % \
  7127. _("An internal error has occurred. See shell.\n")
  7128. msg += traceback.format_exc()
  7129. app_obj.inform.emit(msg)
  7130. return "fail"
  7131. ret = excellon_obj.create_geometry()
  7132. if ret == 'fail':
  7133. log.debug("Could not create geometry for Excellon object.")
  7134. return "fail"
  7135. for tool in excellon_obj.tools:
  7136. if excellon_obj.tools[tool]['solid_geometry']:
  7137. return
  7138. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7139. return "fail"
  7140. with self.proc_container.new(_("Opening Excellon.")):
  7141. # Object name
  7142. name = outname or filename.split('/')[-1].split('\\')[-1]
  7143. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7144. if ret_val == 'fail':
  7145. if from_tcl:
  7146. filename = self.defaults['global_tcl_path'] + '/' + name
  7147. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7148. if ret_val == 'fail':
  7149. self.inform.emit('[ERROR_NOTCL] %s' %
  7150. _('Open Excellon file failed. Probable not an Excellon file.'))
  7151. return
  7152. # Register recent file
  7153. self.file_opened.emit("excellon", filename)
  7154. # AppGUI feedback
  7155. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7156. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7157. """
  7158. Opens a G-gcode file, parses it and creates a new object for
  7159. it in the program. Thread-safe.
  7160. :param filename: G-code file filename
  7161. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7162. :param force_parsing:
  7163. :param plot: If True plot the object on canvas
  7164. :param from_tcl: True if run from Tcl Shell
  7165. :return: None
  7166. """
  7167. App.log.debug("open_gcode()")
  7168. # How the object should be initialized
  7169. def obj_init(job_obj, app_obj_):
  7170. """
  7171. :param job_obj: the resulting object
  7172. :type app_obj_: App
  7173. """
  7174. assert isinstance(app_obj_, App), \
  7175. "Initializer expected App, got %s" % type(app_obj_)
  7176. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7177. try:
  7178. f = open(filename)
  7179. gcode = f.read()
  7180. f.close()
  7181. except IOError:
  7182. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7183. return "fail"
  7184. job_obj.gcode = gcode
  7185. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7186. if gcode_ret == "fail":
  7187. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7188. return "fail"
  7189. job_obj.create_geometry()
  7190. with self.proc_container.new(_("Opening G-Code.")):
  7191. # Object name
  7192. name = outname or filename.split('/')[-1].split('\\')[-1]
  7193. # New object creation and file processing
  7194. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7195. if ret_val == 'fail':
  7196. if from_tcl:
  7197. filename = self.defaults['global_tcl_path'] + '/' + name
  7198. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7199. if ret_val == 'fail':
  7200. self.inform.emit('[ERROR_NOTCL] %s' %
  7201. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7202. "Try to load it from File menu.\n "
  7203. "Attempting to create a FlatCAM CNCJob Object from "
  7204. "G-Code file failed during processing"))
  7205. return "fail"
  7206. # Register recent file
  7207. self.file_opened.emit("cncjob", filename)
  7208. # AppGUI feedback
  7209. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7210. def open_hpgl2(self, filename, outname=None):
  7211. """
  7212. Opens a HPGL2 file, parses it and creates a new object for
  7213. it in the program. Thread-safe.
  7214. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7215. :param filename: HPGL2 file filename
  7216. :return: None
  7217. """
  7218. filename = filename
  7219. # How the object should be initialized
  7220. def obj_init(geo_obj, app_obj):
  7221. assert isinstance(geo_obj, GeometryObject), \
  7222. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7223. # Opening the file happens here
  7224. obj = HPGL2(self)
  7225. try:
  7226. HPGL2.parse_file(obj, filename)
  7227. except IOError:
  7228. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7229. return "fail"
  7230. except ParseError as err:
  7231. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7232. app_obj.log.error(str(err))
  7233. return "fail"
  7234. except Exception as e:
  7235. log.debug("App.open_hpgl2() --> %s" % str(e))
  7236. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7237. msg += traceback.format_exc()
  7238. app_obj.inform.emit(msg)
  7239. return "fail"
  7240. geo_obj.multigeo = True
  7241. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7242. geo_obj.tools = deepcopy(obj.tools)
  7243. geo_obj.source_file = deepcopy(obj.source_file)
  7244. del obj
  7245. if not geo_obj.solid_geometry:
  7246. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7247. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7248. return "fail"
  7249. App.log.debug("open_hpgl2()")
  7250. with self.proc_container.new(_("Opening HPGL2")):
  7251. # Object name
  7252. name = outname or filename.split('/')[-1].split('\\')[-1]
  7253. # # ## Object creation # ##
  7254. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7255. if ret == 'fail':
  7256. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7257. return 'fail'
  7258. # Register recent file
  7259. self.file_opened.emit("geometry", filename)
  7260. # AppGUI feedback
  7261. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7262. def open_script(self, filename, outname=None, silent=False):
  7263. """
  7264. Opens a Script file, parses it and creates a new object for
  7265. it in the program. Thread-safe.
  7266. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7267. :param filename: Script file filename
  7268. :param silent: If True there will be no messages printed to StatusBar
  7269. :return: None
  7270. """
  7271. def obj_init(script_obj, app_obj):
  7272. assert isinstance(script_obj, ScriptObject), \
  7273. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7274. if silent is False:
  7275. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7276. try:
  7277. script_obj.parse_file(filename)
  7278. except IOError:
  7279. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7280. return "fail"
  7281. except ParseError as err:
  7282. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7283. app_obj.log.error(str(err))
  7284. return "fail"
  7285. except Exception as e:
  7286. log.debug("App.open_script() -> %s" % str(e))
  7287. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7288. msg += traceback.format_exc()
  7289. app_obj.inform.emit(msg)
  7290. return "fail"
  7291. App.log.debug("open_script()")
  7292. with self.proc_container.new(_("Opening TCL Script...")):
  7293. # Object name
  7294. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7295. # Object creation
  7296. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7297. if ret_val == 'fail':
  7298. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7299. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7300. if ret_val == 'fail':
  7301. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7302. return 'fail'
  7303. # Register recent file
  7304. self.file_opened.emit("script", filename)
  7305. # AppGUI feedback
  7306. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7307. def open_config_file(self, filename, run_from_arg=None):
  7308. """
  7309. Loads a config file from the specified file.
  7310. :param filename: Name of the file from which to load.
  7311. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7312. :return: None
  7313. """
  7314. App.log.debug("Opening config file: " + filename)
  7315. if run_from_arg:
  7316. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7317. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7318. _("Opening FlatCAM Config file.")),
  7319. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7320. color=QtGui.QColor("gray"))
  7321. # # add the tab if it was closed
  7322. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7323. # # first clear previous text in text editor (if any)
  7324. # self.ui.text_editor_tab.code_editor.clear()
  7325. #
  7326. # # Switch plot_area to CNCJob tab
  7327. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7328. # close the Code editor if already open
  7329. if self.toggle_codeeditor:
  7330. self.on_toggle_code_editor()
  7331. self.on_toggle_code_editor()
  7332. try:
  7333. if filename:
  7334. f = QtCore.QFile(filename)
  7335. if f.open(QtCore.QIODevice.ReadOnly):
  7336. stream = QtCore.QTextStream(f)
  7337. code_edited = stream.readAll()
  7338. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7339. f.close()
  7340. except IOError:
  7341. App.log.error("Failed to open config file: %s" % filename)
  7342. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7343. (_("Failed to open config file"), filename))
  7344. return
  7345. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7346. """
  7347. Loads a project from the specified file.
  7348. 1) Loads and parses file
  7349. 2) Registers the file as recently opened.
  7350. 3) Calls on_file_new()
  7351. 4) Updates options
  7352. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7353. 6) Calls plot_all() if plot=True
  7354. :param filename: Name of the file from which to load.
  7355. :param run_from_arg: True if run for arguments
  7356. :param plot: If True plot all objects in the project
  7357. :param cli: Run from command line
  7358. :param from_tcl: True if run from Tcl Sehll
  7359. :return: None
  7360. """
  7361. App.log.debug("Opening project: " + filename)
  7362. # block autosaving while a project is loaded
  7363. self.block_autosave = True
  7364. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7365. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7366. if cli is None:
  7367. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7368. if run_from_arg:
  7369. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7370. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7371. _("Opening FlatCAM Project file.")),
  7372. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7373. color=QtGui.QColor("gray"))
  7374. # Open and parse an uncompressed Project file
  7375. try:
  7376. f = open(filename, 'r')
  7377. except IOError:
  7378. if from_tcl:
  7379. name = filename.split('/')[-1].split('\\')[-1]
  7380. filename = self.defaults['global_tcl_path'] + '/' + name
  7381. try:
  7382. f = open(filename, 'r')
  7383. except IOError:
  7384. log.error("Failed to open project file: %s" % filename)
  7385. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7386. return
  7387. else:
  7388. log.error("Failed to open project file: %s" % filename)
  7389. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7390. return
  7391. try:
  7392. d = json.load(f, object_hook=dict2obj)
  7393. except Exception as e:
  7394. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7395. (filename, str(e)))
  7396. f.close()
  7397. # Open and parse a compressed Project file
  7398. try:
  7399. with lzma.open(filename) as f:
  7400. file_content = f.read().decode('utf-8')
  7401. d = json.loads(file_content, object_hook=dict2obj)
  7402. except Exception as e:
  7403. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7404. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7405. return
  7406. # Clear the current project
  7407. # # NOT THREAD SAFE # ##
  7408. if run_from_arg is True:
  7409. pass
  7410. elif cli is True:
  7411. self.delete_selection_shape()
  7412. else:
  7413. self.on_file_new()
  7414. # Project options
  7415. self.options.update(d['options'])
  7416. self.project_filename = filename
  7417. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7418. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7419. if cli is None:
  7420. self.set_screen_units(self.options["units"])
  7421. # Re create objects
  7422. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7423. for obj in d['objs']:
  7424. try:
  7425. def obj_init(obj_inst, app_inst):
  7426. obj_inst.from_dict(obj)
  7427. App.log.debug("Recreating from opened project an %s object: %s" %
  7428. (obj['kind'].capitalize(), obj['options']['name']))
  7429. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7430. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7431. if cli is None:
  7432. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7433. obj['kind'].upper(),
  7434. obj['options']['name']
  7435. )
  7436. )
  7437. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7438. except Exception as e:
  7439. print('App.open_project() --> ' + str(e))
  7440. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7441. self.should_we_save = False
  7442. self.file_opened.emit("project", filename)
  7443. # restore autosaving after a project was loaded
  7444. self.block_autosave = False
  7445. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7446. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7447. if cli is None:
  7448. self.set_ui_title(name=self.project_filename)
  7449. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7450. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7451. """
  7452. Re-generates all plots from all objects.
  7453. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7454. :param muted: if True don't print messages
  7455. :param use_thread: if True will use threading for plotting the objects
  7456. :return: None
  7457. """
  7458. self.log.debug("Plot_all()")
  7459. if muted is not True:
  7460. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7461. for plot_obj in self.collection.get_list():
  7462. def worker_task(obj):
  7463. with self.proc_container.new("Plotting"):
  7464. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7465. if fit_view is True:
  7466. self.app_obj.object_plotted.emit(obj)
  7467. if use_thread is True:
  7468. # Send to worker
  7469. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7470. else:
  7471. worker_task(plot_obj)
  7472. def register_folder(self, filename):
  7473. """
  7474. Register the last folder used by the app to open something
  7475. :param filename: the last folder is extracted from the filename
  7476. :return: None
  7477. """
  7478. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7479. def register_save_folder(self, filename):
  7480. """
  7481. Register the last folder used by the app to save something
  7482. :param filename: the last folder is extracted from the filename
  7483. :return: None
  7484. """
  7485. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7486. # def set_progress_bar(self, percentage, text=""):
  7487. # """
  7488. # Set a progress bar to a value (percentage)
  7489. #
  7490. # :param percentage: Value set to the progressbar
  7491. # :param text: Not used
  7492. # :return: None
  7493. # """
  7494. # self.ui.progress_bar.setValue(int(percentage))
  7495. def setup_recent_items(self):
  7496. """
  7497. Setup a dictionary with the recent files accessed, organized by type
  7498. :return:
  7499. """
  7500. icons = {
  7501. "gerber": self.resource_location + "/flatcam_icon16.png",
  7502. "excellon": self.resource_location + "/drill16.png",
  7503. 'geometry': self.resource_location + "/geometry16.png",
  7504. "cncjob": self.resource_location + "/cnc16.png",
  7505. "script": self.resource_location + "/script_new24.png",
  7506. "document": self.resource_location + "/notes16_1.png",
  7507. "project": self.resource_location + "/project16.png",
  7508. "svg": self.resource_location + "/geometry16.png",
  7509. "dxf": self.resource_location + "/dxf16.png",
  7510. "pdf": self.resource_location + "/pdf32.png",
  7511. "image": self.resource_location + "/image16.png"
  7512. }
  7513. try:
  7514. image_opener = self.image_tool.import_image
  7515. except AttributeError:
  7516. image_opener = None
  7517. openers = {
  7518. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7519. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7520. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7521. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7522. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7523. "document": None,
  7524. 'project': self.open_project,
  7525. 'svg': self.import_svg,
  7526. 'dxf': self.import_dxf,
  7527. 'image': image_opener,
  7528. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7529. }
  7530. # Open recent file for files
  7531. try:
  7532. f = open(self.data_path + '/recent.json')
  7533. except IOError:
  7534. App.log.error("Failed to load recent item list.")
  7535. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7536. return
  7537. try:
  7538. self.recent = json.load(f)
  7539. except json.errors.JSONDecodeError:
  7540. App.log.error("Failed to parse recent item list.")
  7541. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7542. f.close()
  7543. return
  7544. f.close()
  7545. # Open recent file for projects
  7546. try:
  7547. fp = open(self.data_path + '/recent_projects.json')
  7548. except IOError:
  7549. App.log.error("Failed to load recent project item list.")
  7550. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7551. return
  7552. try:
  7553. self.recent_projects = json.load(fp)
  7554. except json.errors.JSONDecodeError:
  7555. App.log.error("Failed to parse recent project item list.")
  7556. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7557. fp.close()
  7558. return
  7559. fp.close()
  7560. # Closure needed to create callbacks in a loop.
  7561. # Otherwise late binding occurs.
  7562. def make_callback(func, fname):
  7563. def opener():
  7564. func(fname)
  7565. return opener
  7566. def reset_recent_files():
  7567. # Reset menu
  7568. self.ui.recent.clear()
  7569. self.recent = []
  7570. try:
  7571. ff = open(self.data_path + '/recent.json', 'w')
  7572. except IOError:
  7573. App.log.error("Failed to open recent items file for writing.")
  7574. return
  7575. json.dump(self.recent, ff)
  7576. def reset_recent_projects():
  7577. # Reset menu
  7578. self.ui.recent_projects.clear()
  7579. self.recent_projects = []
  7580. try:
  7581. frp = open(self.data_path + '/recent_projects.json', 'w')
  7582. except IOError:
  7583. App.log.error("Failed to open recent projects items file for writing.")
  7584. return
  7585. json.dump(self.recent, frp)
  7586. # Reset menu
  7587. self.ui.recent.clear()
  7588. self.ui.recent_projects.clear()
  7589. # Create menu items for projects
  7590. for recent in self.recent_projects:
  7591. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7592. if recent['kind'] == 'project':
  7593. try:
  7594. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7595. # Attach callback
  7596. o = make_callback(openers[recent["kind"]], recent['filename'])
  7597. action.triggered.connect(o)
  7598. self.ui.recent_projects.addAction(action)
  7599. except KeyError:
  7600. App.log.error("Unsupported file type: %s" % recent["kind"])
  7601. # Last action in Recent Files menu is one that Clear the content
  7602. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7603. (_("Clear Recent projects")), self)
  7604. clear_action_proj.triggered.connect(reset_recent_projects)
  7605. self.ui.recent_projects.addSeparator()
  7606. self.ui.recent_projects.addAction(clear_action_proj)
  7607. # Create menu items for files
  7608. for recent in self.recent:
  7609. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7610. if recent['kind'] != 'project':
  7611. try:
  7612. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7613. # Attach callback
  7614. o = make_callback(openers[recent["kind"]], recent['filename'])
  7615. action.triggered.connect(o)
  7616. self.ui.recent.addAction(action)
  7617. except KeyError:
  7618. App.log.error("Unsupported file type: %s" % recent["kind"])
  7619. # Last action in Recent Files menu is one that Clear the content
  7620. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7621. (_("Clear Recent files")), self)
  7622. clear_action.triggered.connect(reset_recent_files)
  7623. self.ui.recent.addSeparator()
  7624. self.ui.recent.addAction(clear_action)
  7625. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7626. # self.ui.menufilerecent.set_submenu(recent_menu)
  7627. # recent_menu.show_all()
  7628. # self.ui.recent.show()
  7629. self.log.debug("Recent items list has been populated.")
  7630. def setup_component_editor(self):
  7631. """
  7632. Default text for the Selected tab when is not taken by the Object UI.
  7633. :return:
  7634. """
  7635. # label = QtWidgets.QLabel("Choose an item from Project")
  7636. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7637. sel_title = QtWidgets.QTextEdit(
  7638. _('<b>Shortcut Key List</b>'))
  7639. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7640. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7641. f_settings = QSettings("Open Source", "FlatCAM")
  7642. if f_settings.contains("notebook_font_size"):
  7643. fsize = f_settings.value('notebook_font_size', type=int)
  7644. else:
  7645. fsize = 12
  7646. tsize = fsize + int(fsize / 2)
  7647. # selected_text = (_('''
  7648. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7649. # </p>
  7650. #
  7651. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7652. # The normal flow when working in FlatCAM is the following:</span></p>
  7653. #
  7654. # <ol>
  7655. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7656. # file into
  7657. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7658. # even dragging and dropping the files on the AppGUI.<br />
  7659. # <br />
  7660. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7661. # drop of the
  7662. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7663. # &nbsp;</li>
  7664. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7665. # and then
  7666. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7667. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7668. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7669. # <br />
  7670. # If the selection of the object is done on the canvas by single click instead, and the
  7671. # <strong>SELECTED TAB</strong>
  7672. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7673. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7674. # it even if it was out of focus.<br />
  7675. # <br />
  7676. # You can change the parameters in this screen and the flow direction is like this:<br />
  7677. # <br />
  7678. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7679. # <strong> Geometry Object
  7680. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7681. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7682. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7683. # </ol>
  7684. #
  7685. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7686. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7687. # <strong>F3</strong>.</span></p>
  7688. #
  7689. # ''').format(fsize=fsize, tsize=tsize))
  7690. selected_text = '''
  7691. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7692. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7693. {s1}</span></p>
  7694. <ol>
  7695. <li><span style="font-size:{fsize}px">{s2}<br />
  7696. <br />
  7697. {s3}</span><br />
  7698. &nbsp;</li>
  7699. <li><span style="font-size:{fsize}px">{s4}<br />
  7700. &nbsp;</li>
  7701. <br />
  7702. <li><span style="font-size:{fsize}px">{s5}<br />
  7703. &nbsp;</li>
  7704. <br />
  7705. <li><span style="font-size:{fsize}px">{s6}<br />
  7706. <br />
  7707. {s7}</span></li>
  7708. </ol>
  7709. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7710. '''.format(
  7711. title=_("Selected Tab - Choose an Item from Project Tab"),
  7712. subtitle=_("Details"),
  7713. s1=_("The normal flow when working in FlatCAM is the following:"),
  7714. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7715. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7716. "files on the AppGUI."),
  7717. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7718. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7719. "actions offered within the app."),
  7720. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7721. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7722. "SELECTED TAB will be updated with the object properties according to its kind: "
  7723. "Gerber, Excellon, Geometry or CNCJob object."),
  7724. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7725. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7726. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7727. "the SELECTED TAB and populate it even if it was out of focus."),
  7728. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7729. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7730. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7731. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7732. "(again, done in SELECTED TAB) --> Save GCode."),
  7733. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7734. "or through its own key shortcut: <b>F3</b>."),
  7735. tsize=tsize,
  7736. fsize=fsize
  7737. )
  7738. sel_title.setText(selected_text)
  7739. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7740. self.ui.selected_scroll_area.setWidget(sel_title)
  7741. def setup_obj_classes(self):
  7742. """
  7743. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7744. class.
  7745. :return: None
  7746. """
  7747. FlatCAMObj.app = self
  7748. ObjectCollection.app = self
  7749. Gerber.app = self
  7750. Excellon.app = self
  7751. Geometry.app = self
  7752. CNCjob.app = self
  7753. FCProcess.app = self
  7754. FCProcessContainer.app = self
  7755. OptionsGroupUI.app = self
  7756. def version_check(self):
  7757. """
  7758. Checks for the latest version of the program. Alerts the
  7759. user if theirs is outdated. This method is meant to be run
  7760. in a separate thread.
  7761. :return: None
  7762. """
  7763. self.log.debug("version_check()")
  7764. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7765. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7766. App.version_url,
  7767. str(self.defaults['global_serial']),
  7768. str(self.version),
  7769. str(self.os),
  7770. urllib.parse.urlencode(self.defaults["global_stats"])
  7771. )
  7772. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7773. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7774. # urllib.parse.urlencode(self.defaults["global_stats"])
  7775. else:
  7776. # no_stats dict; just so it won't break things on website
  7777. no_ststs_dict = {}
  7778. no_ststs_dict["global_ststs"] = {}
  7779. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7780. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7781. App.log.debug("Checking for updates @ %s" % full_url)
  7782. # ## Get the data
  7783. try:
  7784. f = urllib.request.urlopen(full_url)
  7785. except Exception:
  7786. # App.log.warning("Failed checking for latest version. Could not connect.")
  7787. self.log.warning("Failed checking for latest version. Could not connect.")
  7788. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7789. return
  7790. try:
  7791. data = json.load(f)
  7792. except Exception as e:
  7793. App.log.error("Could not parse information about latest version.")
  7794. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7795. App.log.debug("json.load(): %s" % str(e))
  7796. f.close()
  7797. return
  7798. f.close()
  7799. # ## Latest version?
  7800. if self.version >= data["version"]:
  7801. App.log.debug("FlatCAM is up to date!")
  7802. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7803. return
  7804. App.log.debug("Newer version available.")
  7805. self.message.emit(
  7806. _("Newer Version Available"),
  7807. '%s<br><br>><b>%s</b><br>%s' % (
  7808. _("There is a newer version of FlatCAM available for download:"),
  7809. str(data["name"]),
  7810. str(data["message"])
  7811. ),
  7812. _("info")
  7813. )
  7814. def on_plotcanvas_setup(self, container=None):
  7815. """
  7816. This is doing the setup for the plot area (canvas).
  7817. :param container: QT Widget where to install the canvas
  7818. :return: None
  7819. """
  7820. if container:
  7821. plot_container = container
  7822. else:
  7823. plot_container = self.ui.right_layout
  7824. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7825. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7826. self.is_legacy = True
  7827. self.defaults["global_graphic_engine"] = "2D"
  7828. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7829. else:
  7830. try:
  7831. self.plotcanvas = PlotCanvas(plot_container, self)
  7832. except Exception as er:
  7833. msg_txt = traceback.format_exc()
  7834. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7835. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7836. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7837. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7838. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7839. msg += msg_txt
  7840. self.inform.emit(msg)
  7841. return 'fail'
  7842. # So it can receive key presses
  7843. self.plotcanvas.native.setFocus()
  7844. if self.is_legacy is False:
  7845. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7846. # Set the mouse button for panning
  7847. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7848. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7849. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7850. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7851. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7852. # Keys over plot enabled
  7853. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7854. if self.defaults['global_cursor_type'] == 'small':
  7855. self.app_cursor = self.plotcanvas.new_cursor()
  7856. else:
  7857. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7858. if self.ui.grid_snap_btn.isChecked():
  7859. self.app_cursor.enabled = True
  7860. else:
  7861. self.app_cursor.enabled = False
  7862. if self.is_legacy is False:
  7863. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7864. else:
  7865. # will use the default Matplotlib axes
  7866. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7867. def on_zoom_fit(self):
  7868. """
  7869. Callback for zoom-fit request. This can be either from the corresponding
  7870. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7871. with axes limits from the geometry bounds of all objects.
  7872. :return: None
  7873. """
  7874. if self.is_legacy is False:
  7875. self.plotcanvas.fit_view()
  7876. else:
  7877. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7878. width = xmax - xmin
  7879. height = ymax - ymin
  7880. xmin -= 0.05 * width
  7881. xmax += 0.05 * width
  7882. ymin -= 0.05 * height
  7883. ymax += 0.05 * height
  7884. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7885. def on_zoom_in(self):
  7886. """
  7887. Callback for zoom-in request.
  7888. :return:
  7889. """
  7890. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7891. def on_zoom_out(self):
  7892. """
  7893. Callback for zoom-out request.
  7894. :return:
  7895. """
  7896. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7897. def disable_all_plots(self):
  7898. self.defaults.report_usage("disable_all_plots()")
  7899. self.disable_plots(self.collection.get_list())
  7900. self.inform.emit('[success] %s' %
  7901. _("All plots disabled."))
  7902. def disable_other_plots(self):
  7903. self.defaults.report_usage("disable_other_plots()")
  7904. self.disable_plots(self.collection.get_non_selected())
  7905. self.inform.emit('[success] %s' %
  7906. _("All non selected plots disabled."))
  7907. def enable_all_plots(self):
  7908. self.defaults.report_usage("enable_all_plots()")
  7909. self.enable_plots(self.collection.get_list())
  7910. self.inform.emit('[success] %s' %
  7911. _("All plots enabled."))
  7912. def on_enable_sel_plots(self):
  7913. log.debug("App.on_enable_sel_plot()")
  7914. object_list = self.collection.get_selected()
  7915. self.enable_plots(objects=object_list)
  7916. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7917. def on_disable_sel_plots(self):
  7918. log.debug("App.on_disable_sel_plot()")
  7919. # self.inform.emit(_("Disabling plots ..."))
  7920. object_list = self.collection.get_selected()
  7921. self.disable_plots(objects=object_list)
  7922. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7923. def enable_plots(self, objects):
  7924. """
  7925. Enable plots
  7926. :param objects: list of Objects to be enabled
  7927. :return:
  7928. """
  7929. log.debug("Enabling plots ...")
  7930. # self.inform.emit(_("Working ..."))
  7931. for obj in objects:
  7932. if obj.options['plot'] is False:
  7933. obj.options.set_change_callback(lambda x: None)
  7934. obj.options['plot'] = True
  7935. try:
  7936. # only the Gerber obj has on_plot_cb_click() method
  7937. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7938. # disable this cb while disconnected,
  7939. # in case the operation takes time the user is not allowed to change it
  7940. obj.ui.plot_cb.setDisabled(True)
  7941. except AttributeError:
  7942. pass
  7943. obj.set_form_item("plot")
  7944. try:
  7945. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7946. obj.ui.plot_cb.setDisabled(False)
  7947. except AttributeError:
  7948. pass
  7949. obj.options.set_change_callback(obj.on_options_change)
  7950. def worker_task(objs):
  7951. with self.proc_container.new(_("Enabling plots ...")):
  7952. for plot_obj in objs:
  7953. # obj.options['plot'] = True
  7954. if isinstance(plot_obj, CNCJobObject):
  7955. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7956. else:
  7957. plot_obj.plot(visible=True)
  7958. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7959. def disable_plots(self, objects):
  7960. """
  7961. Disables plots
  7962. :param objects: list of Objects to be disabled
  7963. :return:
  7964. """
  7965. # if no objects selected then do nothing
  7966. if not self.collection.get_selected():
  7967. return
  7968. log.debug("Disabling plots ...")
  7969. # self.inform.emit(_("Working ..."))
  7970. for obj in objects:
  7971. if obj.options['plot'] is True:
  7972. obj.options.set_change_callback(lambda x: None)
  7973. obj.options['plot'] = False
  7974. try:
  7975. # only the Gerber obj has on_plot_cb_click() method
  7976. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7977. obj.ui.plot_cb.setDisabled(True)
  7978. except AttributeError:
  7979. pass
  7980. obj.set_form_item("plot")
  7981. try:
  7982. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7983. obj.ui.plot_cb.setDisabled(False)
  7984. except AttributeError:
  7985. pass
  7986. obj.options.set_change_callback(obj.on_options_change)
  7987. try:
  7988. self.delete_selection_shape()
  7989. except Exception as e:
  7990. log.debug("App.disable_plots() --> %s" % str(e))
  7991. def worker_task(objs):
  7992. with self.proc_container.new(_("Disabling plots ...")):
  7993. for plot_obj in objs:
  7994. # obj.options['plot'] = True
  7995. if isinstance(plot_obj, CNCJobObject):
  7996. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7997. else:
  7998. plot_obj.plot(visible=False)
  7999. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8000. def toggle_plots(self, objects):
  8001. """
  8002. Toggle plots visibility
  8003. :param objects: list of Objects for which to be toggled the visibility
  8004. :return: None
  8005. """
  8006. # if no objects selected then do nothing
  8007. if not self.collection.get_selected():
  8008. return
  8009. log.debug("Toggling plots ...")
  8010. self.inform.emit(_("Working ..."))
  8011. for obj in objects:
  8012. if obj.options['plot'] is False:
  8013. obj.options['plot'] = True
  8014. else:
  8015. obj.options['plot'] = False
  8016. self.app_obj.plots_updated.emit()
  8017. def clear_plots(self):
  8018. """
  8019. Clear the plots
  8020. :return: None
  8021. """
  8022. objects = self.collection.get_list()
  8023. for obj in objects:
  8024. obj.clear(obj == objects[-1])
  8025. # Clear pool to free memory
  8026. self.clear_pool()
  8027. def on_set_color_action_triggered(self):
  8028. """
  8029. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8030. :return:
  8031. """
  8032. new_color = self.defaults['gerber_plot_fill']
  8033. clicked_action = self.sender()
  8034. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8035. act_name = clicked_action.text()
  8036. sel_obj_list = self.collection.get_selected()
  8037. if not sel_obj_list:
  8038. return
  8039. # a default value, I just chose this one
  8040. alpha_level = 'BF'
  8041. for sel_obj in sel_obj_list:
  8042. if sel_obj.kind == 'excellon':
  8043. alpha_level = str(hex(
  8044. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8045. elif sel_obj.kind == 'gerber':
  8046. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8047. elif sel_obj.kind == 'geometry':
  8048. alpha_level = 'FF'
  8049. else:
  8050. log.debug(
  8051. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8052. continue
  8053. sel_obj.alpha_level = alpha_level
  8054. if act_name == _('Red'):
  8055. new_color = '#FF0000' + alpha_level
  8056. if act_name == _('Blue'):
  8057. new_color = '#0000FF' + alpha_level
  8058. if act_name == _('Yellow'):
  8059. new_color = '#FFDF00' + alpha_level
  8060. if act_name == _('Green'):
  8061. new_color = '#00FF00' + alpha_level
  8062. if act_name == _('Purple'):
  8063. new_color = '#FF00FF' + alpha_level
  8064. if act_name == _('Brown'):
  8065. new_color = '#A52A2A' + alpha_level
  8066. if act_name == _('White'):
  8067. new_color = '#FFFFFF' + alpha_level
  8068. if act_name == _('Black'):
  8069. new_color = '#000000' + alpha_level
  8070. if act_name == _('Custom'):
  8071. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8072. c_dialog = QtWidgets.QColorDialog()
  8073. plot_fill_color = c_dialog.getColor(initial=new_color)
  8074. if plot_fill_color.isValid() is False:
  8075. return
  8076. new_color = str(plot_fill_color.name()) + alpha_level
  8077. if act_name == _("Default"):
  8078. for sel_obj in sel_obj_list:
  8079. if sel_obj.kind == 'excellon':
  8080. new_color = self.defaults['excellon_plot_fill']
  8081. new_line_color = self.defaults['excellon_plot_line']
  8082. elif sel_obj.kind == 'gerber':
  8083. new_color = self.defaults['gerber_plot_fill']
  8084. new_line_color = self.defaults['gerber_plot_line']
  8085. elif sel_obj.kind == 'geometry':
  8086. new_color = self.defaults['geometry_plot_line']
  8087. new_line_color = self.defaults['geometry_plot_line']
  8088. else:
  8089. log.debug(
  8090. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8091. continue
  8092. sel_obj.fill_color = new_color
  8093. sel_obj.outline_color = new_line_color
  8094. sel_obj.shapes.redraw(
  8095. update_colors=(new_color, new_line_color)
  8096. )
  8097. return
  8098. if act_name == _("Opacity"):
  8099. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8100. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8101. if ok_button:
  8102. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8103. for sel_obj in sel_obj_list:
  8104. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8105. sel_obj.shapes.redraw(
  8106. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8107. )
  8108. return
  8109. new_line_color = color_variant(new_color[:7], 0.7)
  8110. if act_name == _("White"):
  8111. new_line_color = color_variant("#dedede", 0.7)
  8112. for sel_obj in sel_obj_list:
  8113. sel_obj.fill_color = new_color
  8114. sel_obj.outline_color = new_line_color
  8115. sel_obj.shapes.redraw(
  8116. update_colors=(new_color, new_line_color)
  8117. )
  8118. def generate_cnc_job(self, objects):
  8119. """
  8120. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8121. :param objects: Selected objects in the Project Tab
  8122. :return:
  8123. """
  8124. self.defaults.report_usage("generate_cnc_job()")
  8125. # for obj in objects:
  8126. # obj.generatecncjob()
  8127. for obj in objects:
  8128. obj.on_generatecnc_button_click()
  8129. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8130. """
  8131. Saves the current project to the specified file.
  8132. :param filename: Name of the file in which to save.
  8133. :type filename: str
  8134. :param quit_action: if the project saving will be followed by an app quit; boolean
  8135. :param silent: if True will not display status messages
  8136. :param from_tcl True is run from Tcl Shell
  8137. :return: None
  8138. """
  8139. self.log.debug("save_project()")
  8140. self.save_in_progress = True
  8141. with self.proc_container.new(_("Saving FlatCAM Project")):
  8142. # Capture the latest changes
  8143. # Current object
  8144. try:
  8145. current_object = self.collection.get_active()
  8146. if current_object:
  8147. current_object.read_form()
  8148. except Exception as e:
  8149. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8150. pass
  8151. # Serialize the whole project
  8152. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8153. "options": self.options,
  8154. "version": self.version}
  8155. if self.defaults["global_save_compressed"] is True:
  8156. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8157. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8158. # # Write
  8159. f.write(g)
  8160. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8161. else:
  8162. # Open file
  8163. try:
  8164. f = open(filename, 'w')
  8165. except IOError:
  8166. App.log.error("Failed to open file for saving: %s", filename)
  8167. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8168. return
  8169. # Write
  8170. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8171. f.close()
  8172. # verification of the saved project
  8173. # Open and parse
  8174. try:
  8175. saved_f = open(filename, 'r')
  8176. except IOError:
  8177. if silent is False:
  8178. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8179. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8180. return
  8181. try:
  8182. saved_d = json.load(saved_f, object_hook=dict2obj)
  8183. except Exception:
  8184. if silent is False:
  8185. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8186. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8187. f.close()
  8188. return
  8189. saved_f.close()
  8190. if silent is False:
  8191. if 'version' in saved_d:
  8192. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8193. else:
  8194. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8195. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8196. tb_settings = QSettings("Open Source", "FlatCAM")
  8197. lock_state = self.ui.lock_action.isChecked()
  8198. tb_settings.setValue('toolbar_lock', lock_state)
  8199. # This will write the setting to the platform specific storage.
  8200. del tb_settings
  8201. # if quit:
  8202. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8203. # t.start()
  8204. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8205. def start_delayed_quit(self, delay, filename, should_quit=None):
  8206. """
  8207. :param delay: period of checking if project file size is more than zero; in seconds
  8208. :param filename: the name of the project file to be checked periodically for size more than zero
  8209. :param should_quit: if the task finished will be followed by an app quit; boolean
  8210. :return:
  8211. """
  8212. to_quit = should_quit
  8213. self.save_timer = QtCore.QTimer()
  8214. self.save_timer.setInterval(delay)
  8215. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8216. self.save_timer.start()
  8217. def check_project_file_size(self, filename, should_quit=None):
  8218. """
  8219. :param filename: the name of the project file to be checked periodically for size more than zero
  8220. :param should_quit: will quit the app if True; boolean
  8221. :return:
  8222. """
  8223. try:
  8224. if os.stat(filename).st_size > 0:
  8225. self.save_in_progress = False
  8226. self.save_timer.stop()
  8227. if should_quit:
  8228. self.app_quit.emit()
  8229. except Exception:
  8230. traceback.print_exc()
  8231. def save_project_auto(self):
  8232. """
  8233. Called periodically to save the project.
  8234. 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
  8235. # progress.
  8236. :return:
  8237. """
  8238. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8239. self.on_file_saveproject()
  8240. def save_project_auto_update(self):
  8241. """
  8242. Update the auto save time interval value.
  8243. :return:
  8244. """
  8245. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8246. try:
  8247. if self.autosave_timer.isActive():
  8248. self.autosave_timer.stop()
  8249. except Exception:
  8250. pass
  8251. if self.defaults['global_autosave'] is True:
  8252. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8253. self.autosave_timer.start()
  8254. def on_options_app2project(self):
  8255. """
  8256. Callback for Options->Transfer Options->App=>Project. Copies options
  8257. from application defaults to project defaults.
  8258. :return: None
  8259. """
  8260. self.defaults.report_usage("on_options_app2project")
  8261. self.preferencesUiManager.defaults_read_form()
  8262. self.options.update(self.defaults)
  8263. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8264. """
  8265. Shows a message on the FlatCAM Shell
  8266. :param msg: Message to display.
  8267. :param show: Opens the shell.
  8268. :param error: Shows the message as an error.
  8269. :param warning: Shows the message as an warning.
  8270. :param success: Shows the message as an success.
  8271. :param selected: Indicate that something was selected on canvas
  8272. :return: None
  8273. """
  8274. if show:
  8275. self.ui.shell_dock.show()
  8276. try:
  8277. if error:
  8278. self.shell.append_error(msg + "\n")
  8279. elif warning:
  8280. self.shell.append_warning(msg + "\n")
  8281. elif success:
  8282. self.shell.append_success(msg + "\n")
  8283. elif selected:
  8284. self.shell.append_selected(msg + "\n")
  8285. else:
  8286. self.shell.append_output(msg + "\n")
  8287. except AttributeError:
  8288. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8289. class ArgsThread(QtCore.QObject):
  8290. open_signal = pyqtSignal(list)
  8291. start = pyqtSignal()
  8292. stop = pyqtSignal()
  8293. if sys.platform == 'win32':
  8294. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8295. else:
  8296. address = ('/tmp/testipc', 'AF_UNIX')
  8297. def __init__(self):
  8298. super(ArgsThread, self).__init__()
  8299. self.listener = None
  8300. self.thread_exit = False
  8301. self.start.connect(self.run)
  8302. self.stop.connect(self.close_listener)
  8303. def my_loop(self, address):
  8304. try:
  8305. self.listener = Listener(*address)
  8306. while self.thread_exit is False:
  8307. conn = self.listener.accept()
  8308. self.serve(conn)
  8309. except socket.error:
  8310. try:
  8311. conn = Client(*address)
  8312. conn.send(sys.argv)
  8313. conn.send('close')
  8314. # close the current instance only if there are args
  8315. if len(sys.argv) > 1:
  8316. try:
  8317. self.listener.close()
  8318. except Exception:
  8319. pass
  8320. sys.exit()
  8321. except ConnectionRefusedError:
  8322. if sys.platform == 'win32':
  8323. pass
  8324. else:
  8325. os.system('rm /tmp/testipc')
  8326. self.listener = Listener(*address)
  8327. while True:
  8328. conn = self.listener.accept()
  8329. self.serve(conn)
  8330. def serve(self, conn):
  8331. while self.thread_exit is False:
  8332. msg = conn.recv()
  8333. if msg == 'close':
  8334. break
  8335. self.open_signal.emit(msg)
  8336. conn.close()
  8337. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8338. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8339. @pyqtSlot()
  8340. def run(self):
  8341. self.my_loop(self.address)
  8342. @pyqtSlot()
  8343. def close_listener(self):
  8344. self.thread_exit = True
  8345. self.listener.close()
  8346. # end of file