app_Main.py 455 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 shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from 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. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from appDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from appObjects.ObjectCollection import *
  50. from appObjects.FlatCAMObj import FlatCAMObj
  51. from appObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from appParsers.ParseExcellon import Excellon
  54. from appParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM appGUI
  57. from appGUI.PlotCanvas import *
  58. from appGUI.PlotCanvasLegacy import *
  59. from appGUI.MainGUI import *
  60. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from appPreProcessor import load_preprocessors
  63. # FlatCAM appEditors
  64. from appEditors.AppGeoEditor import AppGeoEditor
  65. from appEditors.AppExcEditor import AppExcEditor
  66. from appEditors.AppGerberEditor import AppGerberEditor
  67. from appEditors.AppTextEditor import AppTextEditor
  68. from appParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from appProcess import *
  71. from appWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from appTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import appTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = "Unstable Version"
  136. # version = 8.994
  137. version_date = "2020/07/05"
  138. beta = True
  139. engine = '3D'
  140. # current date now
  141. date = str(datetime.today()).rpartition('.')[0]
  142. date = ''.join(c for c in date if c not in ':-')
  143. date = date.replace(' ', '_')
  144. # ###############################################################################################################
  145. # ############################################ URLS's ###########################################################
  146. # ###############################################################################################################
  147. # URL for update checks and statistics
  148. version_url = "http://flatcam.org/version"
  149. # App URL
  150. app_url = "http://flatcam.org"
  151. # Manual URL
  152. manual_url = "http://flatcam.org/manual/index.html"
  153. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  154. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  155. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  156. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  157. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  158. # this variable will hold the project status
  159. # if True it will mean that the project was modified and not saved
  160. should_we_save = False
  161. # flag is True if saving action has been triggered
  162. save_in_progress = False
  163. # ###############################################################################################################
  164. # ####################################### APP Signals ######################################################
  165. # ###############################################################################################################
  166. # Inform the user
  167. # Handled by: App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal([str], [str, bool])
  169. # Handled by: App.info_shell() --> Print on the shell
  170. inform_shell = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. # Emitted when a new object has been added or deleted from/to the collection
  188. object_status_changed = QtCore.pyqtSignal(object, str, str)
  189. message = QtCore.pyqtSignal(str, str, str)
  190. # Emmited when shell command is finished(one command only)
  191. shell_command_finished = QtCore.pyqtSignal(object)
  192. # Emitted when multiprocess pool has been recreated
  193. pool_recreated = QtCore.pyqtSignal(object)
  194. # Emitted when an unhandled exception happens
  195. # in the worker task.
  196. thread_exception = QtCore.pyqtSignal(object)
  197. # used to signal that there are arguments for the app
  198. args_at_startup = QtCore.pyqtSignal(list)
  199. # a reusable signal to replot a list of objects
  200. # should be disconnected after use so it can be reused
  201. replot_signal = pyqtSignal(list)
  202. # signal emitted when jumping
  203. jump_signal = pyqtSignal(tuple)
  204. # signal emitted when jumping
  205. locate_signal = pyqtSignal(tuple, str)
  206. # close app signal
  207. close_app_signal = pyqtSignal()
  208. # will perform the cleanup operation after a Graceful Exit
  209. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  210. # graphic residues behind
  211. cleanup = pyqtSignal()
  212. def __init__(self, user_defaults=True):
  213. """
  214. Starts the application.
  215. :return: app
  216. :rtype: App
  217. """
  218. super().__init__()
  219. App.log.info("FlatCAM Starting...")
  220. # ############################################################################################################
  221. # ################# Setup the listening thread for another instance launching with args ######################
  222. # ############################################################################################################
  223. if sys.platform == 'win32' or sys.platform == 'linux':
  224. # make sure the thread is stored by using a self. otherwise it's garbage collected
  225. self.listen_th = QtCore.QThread()
  226. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  227. self.new_launch = ArgsThread()
  228. self.new_launch.open_signal[list].connect(self.on_startup_args)
  229. self.new_launch.moveToThread(self.listen_th)
  230. self.new_launch.start.emit()
  231. # ############################################################################################################
  232. # ########################################## OS-specific #####################################################
  233. # ############################################################################################################
  234. portable = False
  235. # Folder for user settings.
  236. if sys.platform == 'win32':
  237. if platform.architecture()[0] == '32bit':
  238. App.log.debug("Win32!")
  239. else:
  240. App.log.debug("Win64!")
  241. # #######################################################################################################
  242. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  243. # #######################################################################################################
  244. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  245. try:
  246. with open(config_file, 'r'):
  247. pass
  248. except FileNotFoundError:
  249. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r') as f:
  252. try:
  253. for line in f:
  254. param = str(line).replace('\n', '').rpartition('=')
  255. if param[0] == 'portable':
  256. try:
  257. portable = eval(param[2])
  258. except NameError:
  259. portable = False
  260. if param[0] == 'headless':
  261. if param[2].lower() == 'true':
  262. self.cmd_line_headless = 1
  263. else:
  264. self.cmd_line_headless = None
  265. except Exception as e:
  266. log.debug('App.__init__() -->%s' % str(e))
  267. return
  268. except FileNotFoundError as e:
  269. log.debug(str(e))
  270. pass
  271. if portable is False:
  272. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  273. else:
  274. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  275. self.os = 'windows'
  276. else: # Linux/Unix/MacOS
  277. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  278. self.os = 'unix'
  279. # ############################################################################################################
  280. # ################################# Setup folders and files ##################################################
  281. # ############################################################################################################
  282. if not os.path.exists(self.data_path):
  283. os.makedirs(self.data_path)
  284. App.log.debug('Created data folder: ' + self.data_path)
  285. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  286. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  287. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  288. if not os.path.exists(self.preprocessorpaths):
  289. os.makedirs(self.preprocessorpaths)
  290. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  291. # create geo_tools_db.FlatDB file if there is none
  292. try:
  293. f = open(self.data_path + '/geo_tools_db.FlatDB')
  294. f.close()
  295. except IOError:
  296. App.log.debug('Creating empty geo_tool_db.FlatDB')
  297. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  298. json.dump({}, f)
  299. f.close()
  300. # create current_defaults.FlatConfig file if there is none
  301. try:
  302. f = open(self.data_path + '/current_defaults.FlatConfig')
  303. f.close()
  304. except IOError:
  305. App.log.debug('Creating empty current_defaults.FlatConfig')
  306. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  307. json.dump({}, f)
  308. f.close()
  309. # the factory defaults are written only once at the first launch of the application after installation
  310. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  311. # create a recent files json file if there is none
  312. try:
  313. f = open(self.data_path + '/recent.json')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty recent.json')
  317. f = open(self.data_path + '/recent.json', 'w')
  318. json.dump([], f)
  319. f.close()
  320. # create a recent projects json file if there is none
  321. try:
  322. fp = open(self.data_path + '/recent_projects.json')
  323. fp.close()
  324. except IOError:
  325. App.log.debug('Creating empty recent_projects.json')
  326. fp = open(self.data_path + '/recent_projects.json', 'w')
  327. json.dump([], fp)
  328. fp.close()
  329. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  330. # This will fail under cx_freeze ...
  331. self.app_home = os.path.dirname(os.path.realpath(__file__))
  332. log.debug("Application path is " + self.app_home)
  333. log.debug("Started in " + os.getcwd())
  334. # cx_freeze workaround
  335. if os.path.isfile(self.app_home):
  336. self.app_home = os.path.dirname(self.app_home)
  337. os.chdir(self.app_home)
  338. # ############################################################################################################
  339. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  340. # ############################################################################################################
  341. self.defaults = FlatCAMDefaults()
  342. self.defaults["root_folder_path"] = self.app_home
  343. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  344. if user_defaults:
  345. self.defaults.load(filename=current_defaults_path)
  346. if self.defaults['units'] == 'MM':
  347. self.decimals = int(self.defaults['decimals_metric'])
  348. else:
  349. self.decimals = int(self.defaults['decimals_inch'])
  350. if self.defaults["global_gray_icons"] is False:
  351. self.resource_location = 'assets/resources'
  352. else:
  353. self.resource_location = 'assets/resources/dark_resources'
  354. self.current_units = self.defaults['units']
  355. # ###########################################################################################################
  356. # #################################### SETUP OBJECT CLASSES #################################################
  357. # ###########################################################################################################
  358. self.setup_obj_classes()
  359. # ###########################################################################################################
  360. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  361. # ###########################################################################################################
  362. self.pool = Pool()
  363. # ###########################################################################################################
  364. # ###################################### Clear GUI Settings - once at first start ###########################
  365. # ###########################################################################################################
  366. if self.defaults["first_run"] is True:
  367. # on first run clear the previous QSettings, therefore clearing the GUI settings
  368. qsettings = QSettings("Open Source", "FlatCAM")
  369. for key in qsettings.allKeys():
  370. qsettings.remove(key)
  371. # This will write the setting to the platform specific storage.
  372. del qsettings
  373. # ###########################################################################################################
  374. # ###################################### Setting the Splash Screen ##########################################
  375. # ###########################################################################################################
  376. splash_settings = QSettings("Open Source", "FlatCAM")
  377. if splash_settings.contains("splash_screen"):
  378. show_splash = splash_settings.value("splash_screen")
  379. else:
  380. splash_settings.setValue('splash_screen', 1)
  381. # This will write the setting to the platform specific storage.
  382. del splash_settings
  383. show_splash = 1
  384. if show_splash and self.cmd_line_headless != 1:
  385. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  386. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  387. # self.splash.setMask(splash_pix.mask())
  388. # move splashscreen to the current monitor
  389. desktop = QtWidgets.QApplication.desktop()
  390. screen = desktop.screenNumber(QtGui.QCursor.pos())
  391. current_screen_center = desktop.availableGeometry(screen).center()
  392. self.splash.move(current_screen_center - self.splash.rect().center())
  393. self.splash.show()
  394. self.splash.showMessage(_("FlatCAM is initializing ..."),
  395. alignment=Qt.AlignBottom | Qt.AlignLeft,
  396. color=QtGui.QColor("gray"))
  397. else:
  398. show_splash = 0
  399. # ###########################################################################################################
  400. # ######################################### Initialize GUI ##################################################
  401. # ###########################################################################################################
  402. # FlatCAM colors used in plotting
  403. self.FC_light_green = '#BBF268BF'
  404. self.FC_dark_green = '#006E20BF'
  405. self.FC_light_blue = '#a5a5ffbf'
  406. self.FC_dark_blue = '#0000ffbf'
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. # update the defaults dict with the setting in QSetting
  420. self.defaults['global_theme'] = theme
  421. self.ui = MainGUI(self)
  422. # set FlatCAM units in the Status bar
  423. self.set_screen_units(self.defaults['units'])
  424. # ###########################################################################################################
  425. # ########################################### AUTOSAVE SETUP ################################################
  426. # ###########################################################################################################
  427. self.block_autosave = False
  428. self.autosave_timer = QtCore.QTimer(self)
  429. self.save_project_auto_update()
  430. self.autosave_timer.timeout.connect(self.save_project_auto)
  431. # ###########################################################################################################
  432. # #################################### LOAD PREPROCESSORS ###################################################
  433. # ###########################################################################################################
  434. # ----------------------------------------- WARNING --------------------------------------------------------
  435. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  436. # That's because the number of preprocessors can vary and here the comboboxes are populated
  437. # -----------------------------------------------------------------------------------------------------------
  438. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  439. # the preprocessor file
  440. self.preprocessors = load_preprocessors(self)
  441. # make sure that always the 'default' preprocessor is the first item in the dictionary
  442. if 'default' in self.preprocessors.keys():
  443. new_ppp_dict = {}
  444. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  445. default_pp = self.preprocessors.pop('default')
  446. new_ppp_dict['default'] = default_pp
  447. # then add the rest of the keys
  448. for name, val_class in self.preprocessors.items():
  449. new_ppp_dict[name] = val_class
  450. # and now put back the ordered dict with 'default' key first
  451. self.preprocessors = new_ppp_dict
  452. for name in list(self.preprocessors.keys()):
  453. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  454. if name.partition('_')[0] == 'Paste':
  455. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  456. continue
  457. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  458. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  459. if name == 'hpgl':
  460. continue
  461. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  462. # ###########################################################################################################
  463. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  464. # ###########################################################################################################
  465. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  466. inform=self.inform)
  467. self.preferencesUiManager.defaults_write_form()
  468. # When the self.defaults dictionary changes will update the Preferences GUI forms
  469. self.defaults.set_change_callback(self.on_defaults_dict_change)
  470. # ###########################################################################################################
  471. # ##################################### FIRST RUN SECTION ###################################################
  472. # ################################ It's done only once after install #####################################
  473. # ###########################################################################################################
  474. if self.defaults["first_run"] is True:
  475. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  476. initial_lay = 'minimal'
  477. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  478. # Set the combobox in Preferences to the current layout
  479. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  480. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  481. # after the first run, this object should be False
  482. self.defaults["first_run"] = False
  483. self.preferencesUiManager.save_defaults(silent=True)
  484. # ###########################################################################################################
  485. # ############################################ Data #########################################################
  486. # ###########################################################################################################
  487. self.recent = []
  488. self.recent_projects = []
  489. self.clipboard = QtWidgets.QApplication.clipboard()
  490. self.project_filename = None
  491. self.toggle_units_ignore = False
  492. self.main_thread = QtWidgets.QApplication.instance().thread()
  493. # ###########################################################################################################
  494. # ########################################## LOAD LANGUAGES ################################################
  495. # ###########################################################################################################
  496. self.languages = fcTranslate.load_languages()
  497. for name in sorted(self.languages.values()):
  498. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  499. # ###########################################################################################################
  500. # ####################################### APPLY APP LANGUAGE ################################################
  501. # ###########################################################################################################
  502. ret_val = fcTranslate.apply_language('strings')
  503. if ret_val == "no language":
  504. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  505. log.debug("Could not find the Language files. The App strings are missing.")
  506. else:
  507. # make the current language the current selection on the language combobox
  508. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  509. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  510. # ###########################################################################################################
  511. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  512. # ###########################################################################################################
  513. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  514. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  515. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  516. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  517. self.defaults.propagate_defaults()
  518. # ###########################################################################################################
  519. # ######################################## UPDATE THE OPTIONS ###############################################
  520. # ###########################################################################################################
  521. self.options = LoudDict()
  522. # -----------------------------------------------------------------------------------------------------------
  523. # Update the self.options from the self.defaults
  524. # The self.defaults holds the application defaults while the self.options holds the object defaults
  525. # -----------------------------------------------------------------------------------------------------------
  526. # Copy app defaults to project options
  527. for def_key, def_val in self.defaults.items():
  528. self.options[def_key] = deepcopy(def_val)
  529. self.preferencesUiManager.show_preferences_gui()
  530. # ### End of Data ####
  531. # ###########################################################################################################
  532. # #################################### SETUP OBJECT COLLECTION ##############################################
  533. # ###########################################################################################################
  534. self.collection = ObjectCollection(app=self)
  535. self.ui.project_tab_layout.addWidget(self.collection.view)
  536. self.app_obj = AppObject(app=self)
  537. # ### Adjust tabs width ## ##
  538. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  539. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  540. self.collection.view.setMinimumWidth(290)
  541. self.log.debug("Finished creating Object Collection.")
  542. # ###########################################################################################################
  543. # ######################################## SETUP Plot Area ##################################################
  544. # ###########################################################################################################
  545. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  546. if self.defaults["global_graphic_engine"] == '3D':
  547. self.is_legacy = False
  548. else:
  549. self.is_legacy = True
  550. # Event signals disconnect id holders
  551. self.mp = None
  552. self.mm = None
  553. self.mr = None
  554. self.mdc = None
  555. self.mp_zc = None
  556. self.kp = None
  557. # Matplotlib axis
  558. self.axes = None
  559. if show_splash:
  560. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  561. "Canvas initialization started."),
  562. alignment=Qt.AlignBottom | Qt.AlignLeft,
  563. color=QtGui.QColor("gray"))
  564. start_plot_time = time.time() # debug
  565. self.plotcanvas = None
  566. self.app_cursor = None
  567. self.hover_shapes = None
  568. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  569. # setup the PlotCanvas
  570. self.on_plotcanvas_setup()
  571. end_plot_time = time.time()
  572. self.used_time = end_plot_time - start_plot_time
  573. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  574. if show_splash:
  575. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started.\n"
  577. "Canvas initialization finished in"), '%.2f' % self.used_time),
  578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  579. color=QtGui.QColor("gray"))
  580. self.ui.splitter.setStretchFactor(1, 2)
  581. # ###########################################################################################################
  582. # ############################################### SYS TRAY ##################################################
  583. # ###########################################################################################################
  584. if self.defaults["global_systray_icon"]:
  585. self.parent_w = QtWidgets.QWidget()
  586. if self.cmd_line_headless == 1:
  587. self.trayIcon = FlatCAMSystemTray(app=self,
  588. icon=QtGui.QIcon(self.resource_location +
  589. '/flatcam_icon32_green.png'),
  590. headless=True,
  591. parent=self.parent_w)
  592. else:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. parent=self.parent_w)
  597. # ###########################################################################################################
  598. # ############################################### Worker SETUP ##############################################
  599. # ###########################################################################################################
  600. if self.defaults["global_worker_number"]:
  601. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  602. else:
  603. self.workers = WorkerStack(workers_number=2)
  604. self.worker_task.connect(self.workers.add_task)
  605. self.log.debug("Finished creating Workers crew.")
  606. # ###########################################################################################################
  607. # ############################################# Activity Monitor ###########################################
  608. # ###########################################################################################################
  609. self.activity_view = FlatCAMActivityView(app=self)
  610. self.ui.infobar.addWidget(self.activity_view)
  611. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  612. # ###########################################################################################################
  613. # ############################################# Signal handling #############################################
  614. # ###########################################################################################################
  615. # ########################################## Custom signals ################################################
  616. # signal for displaying messages in status bar
  617. self.inform[str].connect(self.info)
  618. self.inform[str, bool].connect(self.info)
  619. # signal for displaying messages in the shell
  620. self.inform_shell.connect(self.info_shell)
  621. # signal to be called when the app is quiting
  622. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  623. self.message.connect(lambda: message_dialog(parent=self.ui))
  624. # self.progress.connect(self.set_progress_bar)
  625. # signals emitted when file state change
  626. self.file_opened.connect(self.register_recent)
  627. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  628. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  629. # ########################################## Standard signals ###############################################
  630. # ### Menu
  631. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  632. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  633. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  634. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  635. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  636. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  637. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  638. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  639. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  640. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  641. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  642. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  643. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  644. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  645. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  646. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  647. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  648. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  649. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  650. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  651. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  652. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  653. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  654. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  655. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  656. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  657. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  658. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  659. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  660. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  661. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  662. self.ui.menufile_exit.triggered.connect(self.final_save)
  663. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  664. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  665. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  666. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  667. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  668. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  669. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  670. self.ui.menueditdelete.triggered.connect(self.on_delete)
  671. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  672. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  673. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  674. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  675. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  676. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  677. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  678. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  679. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  680. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  681. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  682. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  683. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  684. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  685. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  686. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  687. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  688. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  689. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  690. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  691. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  692. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  693. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  694. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  695. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  696. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  697. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  698. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  699. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  700. self.ui.menuview_replot.triggered.connect(self.plot_all)
  701. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  702. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  703. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  704. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  705. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  706. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  707. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  708. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  709. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  710. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  711. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  712. self.ui.menuhelp_about.triggered.connect(self.on_about)
  713. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  714. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  715. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  716. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  717. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  718. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  719. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  720. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  721. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  722. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  723. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  724. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  725. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  726. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  727. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  728. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  729. # ToolBar signals
  730. self.connect_toolbar_signals(ui=self.ui)
  731. # Notebook and Plot Tab Area signals
  732. # make the right click on the notebook tab and plot tab area tab raise a menu
  733. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  734. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  735. self.on_tab_setup_context_menu()
  736. # activate initial state
  737. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  738. # Context Menu
  739. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  740. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  741. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  742. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  743. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  744. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  745. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  746. self.ui.clearplot.triggered.connect(self.clear_plots)
  747. self.ui.replot.triggered.connect(self.plot_all)
  748. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  749. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  750. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  751. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  752. self.ui.popmenu_move.triggered.connect(self.obj_move)
  753. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  754. # Project Context Menu -> Color Setting
  755. for act in self.ui.menuprojectcolor.actions():
  756. act.triggered.connect(self.on_set_color_action_triggered)
  757. # ###########################################################################################################
  758. # #################################### GUI PREFERENCES SIGNALS ##############################################
  759. # ###########################################################################################################
  760. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  761. lambda: self.on_toggle_units(no_pref=False))
  762. # ##################################### Workspace Setting Signals ###########################################
  763. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  764. self.on_workspace_modified)
  765. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  766. self.on_workspace_modified
  767. )
  768. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  769. # ###########################################################################################################
  770. # ######################################## GUI SETTINGS SIGNALS #############################################
  771. # ###########################################################################################################
  772. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  773. # ######################################## Tools related signals ############################################
  774. # portability changed signal
  775. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  776. # Object list
  777. self.object_status_changed.connect(self.collection.on_collection_updated)
  778. # when there are arguments at application startup this get launched
  779. self.args_at_startup[list].connect(self.on_startup_args)
  780. # ###########################################################################################################
  781. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  782. # ###########################################################################################################
  783. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  784. lambda: self.restore_extensions(ext_type='excellon'))
  785. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  786. lambda: self.restore_extensions(ext_type='gcode'))
  787. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  788. lambda: self.restore_extensions(ext_type='gerber'))
  789. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  790. lambda: self.delete_all_extensions(ext_type='excellon'))
  791. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  792. lambda: self.delete_all_extensions(ext_type='gcode'))
  793. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  794. lambda: self.delete_all_extensions(ext_type='gerber'))
  795. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  796. lambda: self.add_extension(ext_type='excellon'))
  797. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  798. lambda: self.add_extension(ext_type='gcode'))
  799. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  800. lambda: self.add_extension(ext_type='gerber'))
  801. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  802. lambda: self.del_extension(ext_type='excellon'))
  803. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  804. lambda: self.del_extension(ext_type='gcode'))
  805. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  806. lambda: self.del_extension(ext_type='gerber'))
  807. # connect the 'Apply' buttons from the Preferences/File Associations
  808. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  809. lambda: self.on_register_files(obj_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  811. lambda: self.on_register_files(obj_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  813. lambda: self.on_register_files(obj_type='gerber'))
  814. # ###########################################################################################################
  815. # ########################################### KEYWORDS SIGNALS ##############################################
  816. # ###########################################################################################################
  817. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  818. lambda: self.restore_extensions(ext_type='keyword'))
  819. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='keyword'))
  821. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  822. lambda: self.add_extension(ext_type='keyword'))
  823. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  824. lambda: self.del_extension(ext_type='keyword'))
  825. # ###########################################################################################################
  826. # ########################################### GUI SIGNALS ###################################################
  827. # ###########################################################################################################
  828. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  829. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  830. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  831. # ###########################################################################################################
  832. # ####################################### VARIOUS SIGNALS ###################################################
  833. # ###########################################################################################################
  834. # connect the abort_all_tasks related slots to the related signals
  835. self.proc_container.idle_flag.connect(self.app_is_idle)
  836. # signal emitted when a tab is closed in the Plot Area
  837. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  838. # signal to close the application
  839. self.close_app_signal.connect(self.kill_app)
  840. # ################################# FINISHED CONNECTING SIGNALS #############################################
  841. # ###########################################################################################################
  842. # ###########################################################################################################
  843. # ###########################################################################################################
  844. self.log.debug("Finished connecting Signals.")
  845. # ###########################################################################################################
  846. # ########################################## Other setups ###################################################
  847. # ###########################################################################################################
  848. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  849. # depending on from where those tools are called different actions can be done
  850. self.call_source = 'app'
  851. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  852. self.tool_tab_locked = False
  853. # decide if to show or hide the Notebook side of the screen at startup
  854. if self.defaults["global_project_at_startup"] is True:
  855. self.ui.splitter.setSizes([1, 1])
  856. else:
  857. self.ui.splitter.setSizes([0, 1])
  858. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  859. self.setup_component_editor()
  860. # ###########################################################################################################
  861. # ####################################### Auto-complete KEYWORDS ############################################
  862. # ###########################################################################################################
  863. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  864. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  865. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  866. 'export_exc',
  867. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  868. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  869. 'interiors', 'isolate', 'join_excellon',
  870. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  871. 'mirror', 'ncc',
  872. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  873. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  874. 'options', 'origin',
  875. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  876. 'save', 'save_project',
  877. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  878. 'skew', 'subtract_poly', 'subtract_rectangle',
  879. 'version', 'write_gcode'
  880. ]
  881. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  882. 'Paste_1',
  883. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  884. 'Toolchange_manual', 'True', 'Users',
  885. 'all', 'auto', 'axis',
  886. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  887. 'contour', 'default',
  888. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  889. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  890. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  891. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  892. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  893. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  894. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  895. 'spacing_columns',
  896. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  897. 'toolchange_xy', 'toolchangez', 'travelz',
  898. 'tooldia', 'use_threads', 'value',
  899. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  900. ]
  901. self.tcl_keywords = [
  902. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  903. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  904. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  905. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  906. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  907. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  908. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  909. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  910. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  911. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  912. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  913. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  914. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  915. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  916. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  917. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  918. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  919. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  920. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  921. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  922. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  923. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  924. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  925. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  926. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  927. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  928. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  929. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  930. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  931. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  932. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  933. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  934. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  935. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  936. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  937. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  938. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  939. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  940. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  941. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  942. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  943. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  944. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  945. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  946. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  947. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  948. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  949. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  950. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  951. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  952. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  953. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  954. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  955. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  956. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  957. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  958. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  959. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  960. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  961. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  962. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  963. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  964. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  965. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  966. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  967. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  968. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  969. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  970. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  971. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  972. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  973. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  974. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  975. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  976. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  977. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  978. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  979. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  980. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  981. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  982. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  983. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  984. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  985. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  986. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  987. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  988. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  989. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  990. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  991. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  992. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  993. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  994. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  995. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  996. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  997. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  998. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  999. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1000. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1001. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1002. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1003. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1004. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1005. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1006. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1007. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1008. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1009. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1010. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1011. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1012. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1013. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1014. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1015. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1016. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1017. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1018. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1019. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1020. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1021. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1022. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1023. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1024. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1025. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1026. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1027. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1028. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1029. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1030. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1031. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1032. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1033. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1034. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1035. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1036. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1037. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1038. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1039. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1040. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1041. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1042. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1043. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1044. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1045. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1046. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1047. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1048. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1049. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1050. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1051. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1052. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1053. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1054. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1055. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1056. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1057. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1058. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1059. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1060. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1061. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1062. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1063. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1064. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1065. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1066. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1067. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1068. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1069. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1070. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1071. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1072. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1073. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1074. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1075. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1076. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1077. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1078. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1079. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1080. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1081. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1082. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1083. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1084. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1085. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1086. ]
  1087. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1088. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1089. # ###########################################################################################################
  1090. # ########################################## Tools and Plugins ##############################################
  1091. # ###########################################################################################################
  1092. self.shell = None
  1093. self.dblsidedtool = None
  1094. self.distance_tool = None
  1095. self.distance_min_tool = None
  1096. self.panelize_tool = None
  1097. self.film_tool = None
  1098. self.paste_tool = None
  1099. self.calculator_tool = None
  1100. self.rules_tool = None
  1101. self.sub_tool = None
  1102. self.move_tool = None
  1103. self.cutout_tool = None
  1104. self.ncclear_tool = None
  1105. self.paint_tool = None
  1106. self.isolation_tool = None
  1107. self.optimal_tool = None
  1108. self.transform_tool = None
  1109. self.properties_tool = None
  1110. self.pdf_tool = None
  1111. self.image_tool = None
  1112. self.pcb_wizard_tool = None
  1113. self.cal_exc_tool = None
  1114. self.qrcode_tool = None
  1115. self.copper_thieving_tool = None
  1116. self.fiducial_tool = None
  1117. self.edrills_tool = None
  1118. self.align_objects_tool = None
  1119. self.punch_tool = None
  1120. self.invert_tool = None
  1121. self.corners_tool = None
  1122. self.etch_tool = None
  1123. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1124. try:
  1125. self.install_tools()
  1126. except AttributeError as e:
  1127. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1128. # ###########################################################################################################
  1129. # ############################################ SETUP RECENT ITEMS ###########################################
  1130. # ###########################################################################################################
  1131. self.setup_recent_items()
  1132. # ###########################################################################################################
  1133. # ######################################### BookMarks Manager ###############################################
  1134. # ###########################################################################################################
  1135. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1136. self.install_bookmarks()
  1137. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1138. # ###########################################################################################################
  1139. # ########################################### Tools Database ################################################
  1140. # ###########################################################################################################
  1141. self.tools_db_tab = None
  1142. # ### System Font Parsing ###
  1143. # self.f_parse = ParseFont(self)
  1144. # self.parse_system_fonts()
  1145. # ###########################################################################################################
  1146. # ############################################## Shell SETUP ################################################
  1147. # ###########################################################################################################
  1148. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1149. if self.defaults["global_shell_at_startup"]:
  1150. self.ui.shell_dock.show()
  1151. else:
  1152. self.ui.shell_dock.hide()
  1153. # ###########################################################################################################
  1154. # ######################################### Check for updates ###############################################
  1155. # ###########################################################################################################
  1156. # Separate thread (Not worker)
  1157. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1158. if (self.beta is False or self.beta is None) and \
  1159. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1160. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1161. # self.thr2 = QtCore.QThread()
  1162. self.worker_task.emit({'fcn': self.version_check,
  1163. 'params': []})
  1164. # self.thr2.start(QtCore.QThread.LowPriority)
  1165. # ###########################################################################################################
  1166. # ##################################### Register files with FlatCAM; #######################################
  1167. # ################################### It works only for Windows for now ####################################
  1168. # ###########################################################################################################
  1169. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1170. self.on_register_files()
  1171. # ###########################################################################################################
  1172. # ######################################## Variables for global usage #######################################
  1173. # ###########################################################################################################
  1174. # hold the App units
  1175. self.units = 'MM'
  1176. # coordinates for relative position display
  1177. self.rel_point1 = (0, 0)
  1178. self.rel_point2 = (0, 0)
  1179. # variable to store coordinates
  1180. self.pos = (0, 0)
  1181. self.pos_canvas = (0, 0)
  1182. self.pos_jump = (0, 0)
  1183. # variable to store mouse coordinates
  1184. self.mouse = [0, 0]
  1185. # variable to store the delta positions on cavnas
  1186. self.dx = 0
  1187. self.dy = 0
  1188. # decide if we have a double click or single click
  1189. self.doubleclick = False
  1190. # store here the is_dragging value
  1191. self.event_is_dragging = False
  1192. # variable to store if a command is active (then the var is not None) and which one it is
  1193. self.command_active = None
  1194. # variable to store the status of moving selection action
  1195. # None value means that it's not an selection action
  1196. # True value = a selection from left to right
  1197. # False value = a selection from right to left
  1198. self.selection_type = None
  1199. # List to store the objects that are currently loaded in FlatCAM
  1200. # This list is updated on each object creation or object delete
  1201. self.all_objects_list = []
  1202. self.objects_under_the_click_list = []
  1203. # List to store the objects that are selected
  1204. self.sel_objects_list = []
  1205. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1206. self.key_modifiers = None
  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. # last used filters
  1235. self.last_op_gerber_filter = None
  1236. self.last_op_excellon_filter = None
  1237. self.last_op_gcode_filter = None
  1238. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1239. # flag for polygons not cleared
  1240. self.poly_not_cleared = False
  1241. # VisPy visuals
  1242. self.isHovering = False
  1243. self.notHovering = True
  1244. # Window geometry
  1245. self.x_pos = None
  1246. self.y_pos = None
  1247. self.width = None
  1248. self.height = None
  1249. # when True, the app has to return from any thread
  1250. self.abort_flag = False
  1251. # set the value used in the Windows Title
  1252. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1253. # this holds a widget that is installed in the Plot Area when View Source option is used
  1254. self.source_editor_tab = None
  1255. self.pagesize = {}
  1256. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1257. # VisPy visuals
  1258. if self.is_legacy is False:
  1259. try:
  1260. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1261. except AttributeError:
  1262. self.tool_shapes = None
  1263. else:
  1264. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1265. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1266. # used in the delayed shutdown self.start_delayed_quit() method
  1267. self.save_timer = None
  1268. # ###########################################################################################################
  1269. # ################################## ADDING FlatCAM EDITORS section #########################################
  1270. # ###########################################################################################################
  1271. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1272. # at the first launch of the App , the editors will not be functional.
  1273. try:
  1274. self.geo_editor = AppGeoEditor(self)
  1275. except Exception as es:
  1276. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1277. try:
  1278. self.exc_editor = AppExcEditor(self)
  1279. except Exception as es:
  1280. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1281. try:
  1282. self.grb_editor = AppGerberEditor(self)
  1283. except Exception as es:
  1284. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1285. self.log.debug("Finished adding FlatCAM Editor's.")
  1286. self.set_ui_title(name=_("New Project - Not saved"))
  1287. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1288. current_platform = platform.architecture()[0]
  1289. if current_platform != '64bit':
  1290. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1291. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1292. # ###########################################################################################################
  1293. # ########################################### EXCLUSION AREAS ###############################################
  1294. # ###########################################################################################################
  1295. self.exc_areas = ExclusionAreas(app=self)
  1296. # ###########################################################################################################
  1297. # ##################################### Finished the CONSTRUCTOR ############################################
  1298. # ###########################################################################################################
  1299. App.log.debug("END of constructor. Releasing control.")
  1300. # ###########################################################################################################
  1301. # ########################################## SHOW GUI #######################################################
  1302. # ###########################################################################################################
  1303. # if the app is not started as headless, show it
  1304. if self.cmd_line_headless != 1:
  1305. if show_splash:
  1306. # finish the splash
  1307. self.splash.finish(self.ui)
  1308. mgui_settings = QSettings("Open Source", "FlatCAM")
  1309. if mgui_settings.contains("maximized_gui"):
  1310. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1311. if maximized_ui is True:
  1312. self.ui.showMaximized()
  1313. else:
  1314. self.ui.show()
  1315. else:
  1316. self.ui.show()
  1317. if self.defaults["global_systray_icon"]:
  1318. self.trayIcon.show()
  1319. else:
  1320. log.warning("******************* RUNNING HEADLESS *******************")
  1321. # ###########################################################################################################
  1322. # ######################################## START-UP ARGUMENTS ###############################################
  1323. # ###########################################################################################################
  1324. # test if the program was started with a script as parameter
  1325. if self.cmd_line_shellvar:
  1326. try:
  1327. cnt = 0
  1328. command_tcl = 0
  1329. for i in self.cmd_line_shellvar.split(','):
  1330. if i is not None:
  1331. # noinspection PyBroadException
  1332. try:
  1333. command_tcl = eval(i)
  1334. except Exception:
  1335. command_tcl = i
  1336. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1337. cnt += 1
  1338. # if there are Windows paths then replace the path separator with a Unix like one
  1339. if sys.platform == 'win32':
  1340. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1341. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1342. except Exception as ext:
  1343. print("ERROR: ", ext)
  1344. sys.exit(2)
  1345. if self.cmd_line_shellfile:
  1346. if self.cmd_line_headless != 1:
  1347. if self.ui.shell_dock.isHidden():
  1348. self.ui.shell_dock.show()
  1349. try:
  1350. with open(self.cmd_line_shellfile, "r") as myfile:
  1351. # if show_splash:
  1352. # self.splash.showMessage('%s: %ssec\n%s' % (
  1353. # _("Canvas initialization started.\n"
  1354. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1355. # _("Executing Tcl Script ...")),
  1356. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1357. # color=QtGui.QColor("gray"))
  1358. cmd_line_shellfile_text = myfile.read()
  1359. if self.cmd_line_headless != 1:
  1360. self.shell.exec_command(cmd_line_shellfile_text)
  1361. else:
  1362. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1363. except Exception as ext:
  1364. print("ERROR: ", ext)
  1365. sys.exit(2)
  1366. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1367. # the path/file_name must be enclosed in quotes if it contain spaces
  1368. if App.args:
  1369. self.args_at_startup.emit(App.args)
  1370. if self.defaults.old_defaults_found is True:
  1371. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1372. "Please reboot the application to update."))
  1373. self.defaults.old_defaults_found = False
  1374. # ######################################### INIT FINISHED #######################################################
  1375. # #################################################################################################################
  1376. # #################################################################################################################
  1377. # #################################################################################################################
  1378. # #################################################################################################################
  1379. # #################################################################################################################
  1380. @staticmethod
  1381. def copy_and_overwrite(from_path, to_path):
  1382. """
  1383. From here:
  1384. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1385. :param from_path: source path
  1386. :param to_path: destination path
  1387. :return: None
  1388. """
  1389. if os.path.exists(to_path):
  1390. shutil.rmtree(to_path)
  1391. try:
  1392. shutil.copytree(from_path, to_path)
  1393. except FileNotFoundError:
  1394. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1395. shutil.copytree(from_new_path, to_path)
  1396. def on_startup_args(self, args, silent=False):
  1397. """
  1398. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1399. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1400. :param args: a list containing the application args at startup
  1401. :return: None
  1402. """
  1403. if args is not None:
  1404. args_to_process = args
  1405. else:
  1406. args_to_process = App.args
  1407. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1408. for argument in args_to_process:
  1409. if '.FlatPrj'.lower() in argument.lower():
  1410. try:
  1411. project_name = str(argument)
  1412. if project_name == "":
  1413. if silent is False:
  1414. self.inform.emit(_("Cancelled."))
  1415. else:
  1416. # self.open_project(project_name)
  1417. run_from_arg = True
  1418. # self.worker_task.emit({'fcn': self.open_project,
  1419. # 'params': [project_name, run_from_arg]})
  1420. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1421. except Exception as e:
  1422. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1423. elif '.FlatConfig'.lower() in argument.lower():
  1424. try:
  1425. file_name = str(argument)
  1426. if file_name == "":
  1427. if silent is False:
  1428. self.inform.emit(_("Open Config file failed."))
  1429. else:
  1430. run_from_arg = True
  1431. # self.worker_task.emit({'fcn': self.open_config_file,
  1432. # 'params': [file_name, run_from_arg]})
  1433. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1434. except Exception as e:
  1435. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1436. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1437. try:
  1438. file_name = str(argument)
  1439. if file_name == "":
  1440. if silent is False:
  1441. self.inform.emit(_("Open Script file failed."))
  1442. else:
  1443. if silent is False:
  1444. self.on_fileopenscript(name=file_name)
  1445. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1446. self.on_filerunscript(name=file_name)
  1447. except Exception as e:
  1448. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1449. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1450. log.debug("App.on_startup_args() --> Quit event.")
  1451. sys.exit()
  1452. elif 'save'.lower() in argument.lower():
  1453. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1454. self.preferencesUiManager.save_defaults()
  1455. else:
  1456. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1457. proc_arg = argument.lower()
  1458. for ext in exc_list:
  1459. proc_ext = ext.replace(' ', '')
  1460. proc_ext = '.%s' % proc_ext
  1461. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1462. file_name = str(argument)
  1463. if file_name == "":
  1464. if silent is False:
  1465. self.inform.emit(_("Open Excellon file failed."))
  1466. else:
  1467. self.on_fileopenexcellon(name=file_name, signal=None)
  1468. return
  1469. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1470. for ext in gco_list:
  1471. proc_ext = ext.replace(' ', '')
  1472. proc_ext = '.%s' % proc_ext
  1473. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1474. file_name = str(argument)
  1475. if file_name == "":
  1476. if silent is False:
  1477. self.inform.emit(_("Open GCode file failed."))
  1478. else:
  1479. self.on_fileopengcode(name=file_name, signal=None)
  1480. return
  1481. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1482. for ext in grb_list:
  1483. proc_ext = ext.replace(' ', '')
  1484. proc_ext = '.%s' % proc_ext
  1485. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1486. file_name = str(argument)
  1487. if file_name == "":
  1488. if silent is False:
  1489. self.inform.emit(_("Open Gerber file failed."))
  1490. else:
  1491. self.on_fileopengerber(name=file_name, signal=None)
  1492. return
  1493. # if it reached here without already returning then the app was registered with a file that it does not
  1494. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1495. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1496. # for arg in args_to_process:
  1497. # if 'FlatCAM.exe' in arg:
  1498. # continue
  1499. # else:
  1500. # sys.exit(2)
  1501. def set_ui_title(self, name):
  1502. """
  1503. Sets the title of the main window.
  1504. :param name: String that store the project path and project name
  1505. :return: None
  1506. """
  1507. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1508. (self.version,
  1509. ('BETA' if self.beta else ''),
  1510. platform.architecture()[0],
  1511. self.engine,
  1512. name)
  1513. )
  1514. def on_app_restart(self):
  1515. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1516. # be left in the SySTray
  1517. try:
  1518. self.trayIcon.hide()
  1519. except Exception:
  1520. pass
  1521. fcTranslate.restart_program(app=self)
  1522. def clear_pool(self):
  1523. """
  1524. Clear the multiprocessing pool and calls garbage collector.
  1525. :return: None
  1526. """
  1527. self.pool.close()
  1528. self.pool = Pool()
  1529. self.pool_recreated.emit(self.pool)
  1530. gc.collect()
  1531. def install_tools(self):
  1532. """
  1533. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1534. Instantiation of the Tools classes.
  1535. The order that the tools are installed is important as they can depend on each other install position.
  1536. :return: None
  1537. """
  1538. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1539. self.shell = FCShell(app=self, version=self.version)
  1540. self.distance_tool = Distance(self)
  1541. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1542. before=self.ui.menueditorigin,
  1543. separator=False)
  1544. self.distance_min_tool = DistanceMin(self)
  1545. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1546. pos=self.ui.menuedit,
  1547. before=self.ui.menueditorigin,
  1548. separator=True)
  1549. self.dblsidedtool = DblSidedTool(self)
  1550. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1551. self.cal_exc_tool = ToolCalibration(self)
  1552. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1553. before=self.dblsidedtool.menuAction,
  1554. separator=False)
  1555. self.align_objects_tool = AlignObjects(self)
  1556. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1557. self.edrills_tool = ToolExtractDrills(self)
  1558. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1559. self.panelize_tool = Panelize(self)
  1560. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1561. self.film_tool = Film(self)
  1562. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1563. self.paste_tool = SolderPaste(self)
  1564. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1565. self.calculator_tool = ToolCalculator(self)
  1566. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1567. self.sub_tool = ToolSub(self)
  1568. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1569. pos=self.ui.menutool, separator=True)
  1570. self.rules_tool = RulesCheck(self)
  1571. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1572. pos=self.ui.menutool, separator=False)
  1573. self.optimal_tool = ToolOptimal(self)
  1574. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1575. pos=self.ui.menutool, separator=True)
  1576. self.move_tool = ToolMove(self)
  1577. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1578. before=self.ui.menueditorigin, separator=True)
  1579. self.cutout_tool = CutOut(self)
  1580. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1581. before=self.sub_tool.menuAction)
  1582. self.ncclear_tool = NonCopperClear(self)
  1583. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1584. before=self.sub_tool.menuAction, separator=True)
  1585. self.paint_tool = ToolPaint(self)
  1586. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1587. before=self.sub_tool.menuAction, separator=True)
  1588. self.isolation_tool = ToolIsolation(self)
  1589. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction, separator=True)
  1591. self.copper_thieving_tool = ToolCopperThieving(self)
  1592. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1593. pos=self.ui.menutool)
  1594. self.fiducial_tool = ToolFiducials(self)
  1595. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1596. pos=self.ui.menutool)
  1597. self.qrcode_tool = QRCode(self)
  1598. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1599. pos=self.ui.menutool)
  1600. self.punch_tool = ToolPunchGerber(self)
  1601. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1602. self.invert_tool = ToolInvertGerber(self)
  1603. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1604. self.corners_tool = ToolCorners(self)
  1605. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1606. self.etch_tool = ToolEtchCompensation(self)
  1607. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1608. self.transform_tool = ToolTransform(self)
  1609. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1610. pos=self.ui.menuoptions, separator=True)
  1611. self.properties_tool = Properties(self)
  1612. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1613. pos=self.ui.menuoptions)
  1614. self.pdf_tool = ToolPDF(self)
  1615. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1616. pos=self.ui.menufileimport,
  1617. separator=True)
  1618. self.image_tool = ToolImage(self)
  1619. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1620. pos=self.ui.menufileimport,
  1621. separator=True)
  1622. self.pcb_wizard_tool = PcbWizard(self)
  1623. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1624. pos=self.ui.menufileimport)
  1625. self.log.debug("Tools are installed.")
  1626. def remove_tools(self):
  1627. """
  1628. Will remove all the actions in the Tool menu.
  1629. :return: None
  1630. """
  1631. for act in self.ui.menutool.actions():
  1632. self.ui.menutool.removeAction(act)
  1633. def init_tools(self):
  1634. """
  1635. Initialize the Tool tab in the notebook side of the central widget.
  1636. Remove the actions in the Tools menu.
  1637. Instantiate again the FlatCAM tools (plugins).
  1638. All this is required when changing the layout: standard, compact etc.
  1639. :return: None
  1640. """
  1641. log.debug("init_tools()")
  1642. # delete the data currently in the Tools Tab and the Tab itself
  1643. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1644. if widget is not None:
  1645. widget.deleteLater()
  1646. self.ui.notebook.removeTab(2)
  1647. # rebuild the Tools Tab
  1648. self.ui.tool_tab = QtWidgets.QWidget()
  1649. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1650. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1651. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1652. self.ui.tool_scroll_area = VerticalScrollArea()
  1653. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1654. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1655. # first remove all of them
  1656. self.remove_tools()
  1657. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1658. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1659. '&Command Line\tS')
  1660. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1661. # third install all of them
  1662. try:
  1663. self.install_tools()
  1664. except AttributeError:
  1665. pass
  1666. self.log.debug("Tools are initialized.")
  1667. # def parse_system_fonts(self):
  1668. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1669. # 'params': []})
  1670. def connect_tools_signals_to_toolbar(self, ui):
  1671. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1672. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1673. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1674. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1675. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1676. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1677. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1678. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1679. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1680. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1681. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1682. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1683. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1684. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1685. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1686. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1687. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1688. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1689. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1690. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1691. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1692. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1693. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1694. def connect_toolbar_signals(self, ui):
  1695. """
  1696. Reconnect the signals to the actions in the toolbar.
  1697. This has to be done each time after the FlatCAM tools are removed/installed.
  1698. :return: None
  1699. """
  1700. # Toolbar
  1701. # File Toolbar Signals
  1702. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1703. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1704. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1705. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1706. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1707. # View Toolbar Signals
  1708. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1709. ui.replot_btn.triggered.connect(self.plot_all)
  1710. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1711. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1712. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1713. # Edit Toolbar Signals
  1714. ui.editgeo_btn.triggered.connect(self.object2editor)
  1715. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1716. ui.copy_btn.triggered.connect(self.on_copy_command)
  1717. ui.delete_btn.triggered.connect(self.on_delete)
  1718. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1719. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1720. ui.origin_btn.triggered.connect(self.on_set_origin)
  1721. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1722. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1723. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1724. # Scripting Toolbar Signals
  1725. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1726. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1727. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1728. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1729. # Tools Toolbar Signals
  1730. try:
  1731. self.connect_tools_signals_to_toolbar(ui=ui)
  1732. except Exception as err:
  1733. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1734. def object2editor(self):
  1735. """
  1736. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1737. :return: None
  1738. """
  1739. self.defaults.report_usage("object2editor()")
  1740. # disable the objects menu as it may interfere with the appEditors
  1741. self.ui.menuobjects.setDisabled(True)
  1742. edited_object = self.collection.get_active()
  1743. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1744. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1745. pass
  1746. else:
  1747. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1748. return
  1749. if isinstance(edited_object, GeometryObject):
  1750. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1751. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1752. # we set the notebook to hidden
  1753. # self.ui.splitter.setSizes([0, 1])
  1754. if edited_object.multigeo is True:
  1755. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1756. if len(sel_rows) > 1:
  1757. self.inform.emit('[WARNING_NOTCL] %s' %
  1758. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1759. "is not possible.\n"
  1760. "Edit only one geometry at a time."))
  1761. if not sel_rows:
  1762. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1763. return
  1764. # determine the tool dia of the selected tool
  1765. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1766. # now find the key in the edited_object.tools that has this tooldia
  1767. multi_tool = 1
  1768. for tool in edited_object.tools:
  1769. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1770. multi_tool = tool
  1771. break
  1772. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1773. else:
  1774. self.geo_editor.edit_fcgeometry(edited_object)
  1775. # set call source to the Editor we go into
  1776. self.call_source = 'geo_editor'
  1777. elif isinstance(edited_object, ExcellonObject):
  1778. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1779. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1780. if self.ui.splitter.sizes()[0] == 0:
  1781. self.ui.splitter.setSizes([1, 1])
  1782. self.exc_editor.edit_fcexcellon(edited_object)
  1783. # set call source to the Editor we go into
  1784. self.call_source = 'exc_editor'
  1785. elif isinstance(edited_object, GerberObject):
  1786. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1787. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1788. if self.ui.splitter.sizes()[0] == 0:
  1789. self.ui.splitter.setSizes([1, 1])
  1790. self.grb_editor.edit_fcgerber(edited_object)
  1791. # set call source to the Editor we go into
  1792. self.call_source = 'grb_editor'
  1793. # reset the following variables so the UI is built again after edit
  1794. edited_object.ui_build = False
  1795. edited_object.build_aperture_storage = False
  1796. elif isinstance(edited_object, CNCJobObject):
  1797. if self.ui.splitter.sizes()[0] == 0:
  1798. self.ui.splitter.setSizes([1, 1])
  1799. edited_object.on_edit_code_click()
  1800. return
  1801. # make sure that we can't select another object while in Editor Mode:
  1802. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1803. self.ui.project_frame.setDisabled(True)
  1804. # delete any selection shape that might be active as they are not relevant in Editor
  1805. self.delete_selection_shape()
  1806. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1807. self.ui.plot_tab_area.protectTab(0)
  1808. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1809. self.should_we_save = True
  1810. def editor2object(self, cleanup=None):
  1811. """
  1812. Transfers the Geometry or Excellon from it's editor to the current object.
  1813. :return: None
  1814. """
  1815. self.defaults.report_usage("editor2object()")
  1816. # re-enable the objects menu that was disabled on entry in Editor mode
  1817. self.ui.menuobjects.setDisabled(False)
  1818. # do not update a geometry or excellon object unless it comes out of an editor
  1819. if self.call_source != 'app':
  1820. edited_obj = self.collection.get_active()
  1821. if cleanup is None:
  1822. msgbox = QtWidgets.QMessageBox()
  1823. msgbox.setText(_("Do you want to save the edited object?"))
  1824. msgbox.setWindowTitle(_("Close Editor"))
  1825. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1826. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1827. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1828. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1829. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1830. msgbox.setDefaultButton(bt_yes)
  1831. msgbox.exec_()
  1832. response = msgbox.clickedButton()
  1833. if response == bt_yes:
  1834. # clean the Tools Tab
  1835. self.ui.tool_scroll_area.takeWidget()
  1836. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1837. self.ui.notebook.setTabText(2, "Tool")
  1838. if isinstance(edited_obj, GeometryObject):
  1839. obj_type = "Geometry"
  1840. self.geo_editor.update_fcgeometry(edited_obj)
  1841. # self.geo_editor.update_options(edited_obj)
  1842. # restore GUI to the Selected TAB
  1843. # Remove anything else in the appGUI
  1844. self.ui.tool_scroll_area.takeWidget()
  1845. # update the geo object options so it is including the bounding box values
  1846. try:
  1847. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1848. edited_obj.options['xmin'] = xmin
  1849. edited_obj.options['ymin'] = ymin
  1850. edited_obj.options['xmax'] = xmax
  1851. edited_obj.options['ymax'] = ymax
  1852. except AttributeError as e:
  1853. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1854. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1855. edited_obj.build_ui()
  1856. edited_obj.plot()
  1857. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1858. elif isinstance(edited_obj, GerberObject):
  1859. obj_type = "Gerber"
  1860. self.grb_editor.update_fcgerber()
  1861. # self.grb_editor.update_options(edited_obj)
  1862. # delete the old object (the source object) if it was an empty one
  1863. try:
  1864. if len(edited_obj.solid_geometry) == 0:
  1865. old_name = edited_obj.options['name']
  1866. self.collection.delete_by_name(old_name)
  1867. except TypeError:
  1868. # if the solid_geometry is a single Polygon the len() will not work
  1869. # in any case, falling here means that we have something in the solid_geometry, even if only
  1870. # a single Polygon, therefore we pass this
  1871. pass
  1872. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1873. # restore GUI to the Selected TAB
  1874. # Remove anything else in the appGUI
  1875. self.ui.selected_scroll_area.takeWidget()
  1876. elif isinstance(edited_obj, ExcellonObject):
  1877. obj_type = "Excellon"
  1878. self.exc_editor.update_fcexcellon(edited_obj)
  1879. # self.exc_editor.update_options(edited_obj)
  1880. # restore GUI to the Selected TAB
  1881. # Remove anything else in the appGUI
  1882. self.ui.tool_scroll_area.takeWidget()
  1883. # delete the old object (the source object) if it was an empty one
  1884. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1885. old_name = edited_obj.options['name']
  1886. self.collection.delete_by_name(name=old_name)
  1887. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1888. else:
  1889. self.inform.emit('[WARNING_NOTCL] %s' %
  1890. _("Select a Gerber, Geometry or Excellon Object to update."))
  1891. return
  1892. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1893. elif response == bt_no:
  1894. # clean the Tools Tab
  1895. self.ui.tool_scroll_area.takeWidget()
  1896. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1897. self.ui.notebook.setTabText(2, "Tool")
  1898. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1899. if isinstance(edited_obj, GeometryObject):
  1900. self.geo_editor.deactivate()
  1901. edited_obj.build_ui()
  1902. edited_obj.plot()
  1903. elif isinstance(edited_obj, GerberObject):
  1904. self.grb_editor.deactivate_grb_editor()
  1905. edited_obj.build_ui()
  1906. elif isinstance(edited_obj, ExcellonObject):
  1907. self.exc_editor.deactivate()
  1908. edited_obj.build_ui()
  1909. else:
  1910. self.inform.emit('[WARNING_NOTCL] %s' %
  1911. _("Select a Gerber, Geometry or Excellon Object to update."))
  1912. return
  1913. elif response == bt_cancel:
  1914. return
  1915. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1916. # edited_obj.build_ui()
  1917. # Switch notebook to Selected page
  1918. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1919. else:
  1920. if isinstance(edited_obj, GeometryObject):
  1921. self.geo_editor.deactivate()
  1922. elif isinstance(edited_obj, GerberObject):
  1923. self.grb_editor.deactivate_grb_editor()
  1924. elif isinstance(edited_obj, ExcellonObject):
  1925. self.exc_editor.deactivate()
  1926. else:
  1927. self.inform.emit('[WARNING_NOTCL] %s' %
  1928. _("Select a Gerber, Geometry or Excellon Object to update."))
  1929. return
  1930. # if notebook is hidden we show it
  1931. if self.ui.splitter.sizes()[0] == 0:
  1932. self.ui.splitter.setSizes([1, 1])
  1933. # restore the call_source to app
  1934. self.call_source = 'app'
  1935. # edited_obj.plot()
  1936. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1937. self.ui.plot_tab_area.protectTab(0)
  1938. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1939. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1940. self.ui.project_frame.setDisabled(False)
  1941. def get_last_folder(self):
  1942. """
  1943. Get the folder path from where the last file was opened.
  1944. :return: String, last opened folder path
  1945. """
  1946. return self.defaults["global_last_folder"]
  1947. def get_last_save_folder(self):
  1948. """
  1949. Get the folder path from where the last file was saved.
  1950. :return: String, last saved folder path
  1951. """
  1952. loc = self.defaults["global_last_save_folder"]
  1953. if loc is None:
  1954. loc = self.defaults["global_last_folder"]
  1955. if loc is None:
  1956. loc = os.path.dirname(__file__)
  1957. return loc
  1958. @QtCore.pyqtSlot(str)
  1959. @QtCore.pyqtSlot(str, bool)
  1960. def info(self, msg, shell_echo=True):
  1961. """
  1962. Informs the user. Normally on the status bar, optionally
  1963. also on the shell.
  1964. :param msg: Text to write.
  1965. :type msg: str
  1966. :param shell_echo: Control if to display the message msg in the Shell
  1967. :type shell_echo: bool
  1968. :return: None
  1969. """
  1970. # Type of message in brackets at the beginning of the message.
  1971. match = re.search(r"\[(.*)\](.*)", msg)
  1972. if match:
  1973. level = match.group(1)
  1974. msg_ = match.group(2)
  1975. self.ui.fcinfo.set_status(str(msg_), level=level)
  1976. if shell_echo is True:
  1977. if level.lower() == "error":
  1978. self.shell_message(msg, error=True, show=True)
  1979. elif level.lower() == "warning":
  1980. self.shell_message(msg, warning=True, show=True)
  1981. elif level.lower() == "error_notcl":
  1982. self.shell_message(msg, error=True, show=False)
  1983. elif level.lower() == "warning_notcl":
  1984. self.shell_message(msg, warning=True, show=False)
  1985. elif level.lower() == "success":
  1986. self.shell_message(msg, success=True, show=False)
  1987. elif level.lower() == "selected":
  1988. self.shell_message(msg, selected=True, show=False)
  1989. else:
  1990. self.shell_message(msg, show=False)
  1991. else:
  1992. self.ui.fcinfo.set_status(str(msg), level="info")
  1993. # make sure that if the message is to clear the infobar with a space
  1994. # is not printed over and over on the shell
  1995. if msg != '' and shell_echo is True:
  1996. self.shell_message(msg)
  1997. def info_shell(self, msg):
  1998. self.shell_message(msg=msg)
  1999. def on_import_preferences(self):
  2000. """
  2001. Loads the application default settings from a saved file into
  2002. ``self.defaults`` dictionary.
  2003. :return: None
  2004. """
  2005. self.defaults.report_usage("on_import_preferences")
  2006. App.log.debug("App.on_import_preferences()")
  2007. # Show file chooser
  2008. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2009. try:
  2010. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2011. directory=self.data_path,
  2012. filter=filter_)
  2013. except TypeError:
  2014. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2015. filter=filter_)
  2016. filename = str(filename)
  2017. if filename == "":
  2018. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2019. return
  2020. # Load in the defaults from the chosen file
  2021. self.defaults.load(filename=filename)
  2022. self.preferencesUiManager.on_preferences_edited()
  2023. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2024. def on_export_preferences(self):
  2025. """
  2026. Save the defaults dictionary to a file.
  2027. :return: None
  2028. """
  2029. self.defaults.report_usage("on_export_preferences")
  2030. App.log.debug("on_export_preferences()")
  2031. # defaults_file_content = None
  2032. # Show file chooser
  2033. date = str(datetime.today()).rpartition('.')[0]
  2034. date = ''.join(c for c in date if c not in ':-')
  2035. date = date.replace(' ', '_')
  2036. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2037. try:
  2038. filename, _f = FCFileSaveDialog.get_saved_filename(
  2039. caption=_("Export FlatCAM Preferences"),
  2040. directory=self.data_path + '/preferences_' + date,
  2041. ext_filter=filter__
  2042. )
  2043. except TypeError:
  2044. filename, _f = FCFileSaveDialog.get_saved_filename(
  2045. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2046. filename = str(filename)
  2047. if filename == "":
  2048. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2049. return
  2050. # Update options
  2051. self.preferencesUiManager.defaults_read_form()
  2052. self.defaults.propagate_defaults()
  2053. # Save update options
  2054. try:
  2055. self.defaults.write(filename=filename)
  2056. except Exception:
  2057. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2058. return
  2059. if self.defaults["global_open_style"] is False:
  2060. self.file_opened.emit("preferences", filename)
  2061. self.file_saved.emit("preferences", filename)
  2062. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2063. def save_to_file(self, content_to_save, txt_content):
  2064. """
  2065. Save something to a file.
  2066. :return: None
  2067. """
  2068. self.defaults.report_usage("save_to_file")
  2069. App.log.debug("save_to_file()")
  2070. self.date = str(datetime.today()).rpartition('.')[0]
  2071. self.date = ''.join(c for c in self.date if c not in ':-')
  2072. self.date = self.date.replace(' ', '_')
  2073. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2074. path_to_save = self.defaults["global_last_save_folder"] if \
  2075. self.defaults["global_last_save_folder"] is not None else self.data_path
  2076. try:
  2077. filename, _f = FCFileSaveDialog.get_saved_filename(
  2078. caption=_("Save to file"),
  2079. directory=path_to_save + '/file_' + self.date,
  2080. ext_filter=filter__
  2081. )
  2082. except TypeError:
  2083. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2084. filename = str(filename)
  2085. if filename == "":
  2086. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2087. return
  2088. else:
  2089. try:
  2090. with open(filename, 'w') as f:
  2091. ___ = f.read()
  2092. except PermissionError:
  2093. self.inform.emit('[WARNING] %s' %
  2094. _("Permission denied, saving not possible.\n"
  2095. "Most likely another app is holding the file open and not accessible."))
  2096. return
  2097. except IOError:
  2098. App.log.debug('Creating a new file ...')
  2099. f = open(filename, 'w')
  2100. f.close()
  2101. except Exception:
  2102. e = sys.exc_info()[0]
  2103. App.log.error("Could not load the file.")
  2104. App.log.error(str(e))
  2105. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2106. return
  2107. # Save content
  2108. if filename.rpartition('.')[2].lower() == 'html':
  2109. file_content = content_to_save
  2110. else:
  2111. file_content = txt_content
  2112. try:
  2113. with open(filename, "w") as f:
  2114. f.write(file_content)
  2115. except Exception:
  2116. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2117. return
  2118. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2119. def register_recent(self, kind, filename):
  2120. """
  2121. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2122. dictionary.
  2123. :param kind: type of file that was opened
  2124. :param filename: the path and file name for the file that was opened
  2125. :return:
  2126. """
  2127. self.log.debug("register_recent()")
  2128. self.log.debug(" %s" % kind)
  2129. self.log.debug(" %s" % filename)
  2130. record = {'kind': str(kind), 'filename': str(filename)}
  2131. if record in self.recent:
  2132. return
  2133. if record in self.recent_projects:
  2134. return
  2135. if record['kind'] == 'project':
  2136. self.recent_projects.insert(0, record)
  2137. else:
  2138. self.recent.insert(0, record)
  2139. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2140. self.recent.pop()
  2141. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2142. self.recent_projects.pop()
  2143. try:
  2144. f = open(self.data_path + '/recent.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 files file for writing.'))
  2149. return
  2150. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2151. f.close()
  2152. try:
  2153. fp = open(self.data_path + '/recent_projects.json', 'w')
  2154. except IOError:
  2155. App.log.error("Failed to open recent items file for writing.")
  2156. self.inform.emit('[ERROR_NOTCL] %s' %
  2157. _('Failed to open recent projects file for writing.'))
  2158. return
  2159. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2160. fp.close()
  2161. # Re-build the recent items menu
  2162. self.setup_recent_items()
  2163. def on_about(self):
  2164. """
  2165. Displays the "about" dialog found in the Menu --> Help.
  2166. :return: None
  2167. """
  2168. self.defaults.report_usage("on_about")
  2169. version = self.version
  2170. version_date = self.version_date
  2171. beta = self.beta
  2172. class AboutDialog(QtWidgets.QDialog):
  2173. def __init__(self, app, parent=None):
  2174. QtWidgets.QDialog.__init__(self, parent)
  2175. self.app = app
  2176. # Icon and title
  2177. self.setWindowIcon(parent.app_icon)
  2178. self.setWindowTitle(_("About FlatCAM"))
  2179. self.resize(600, 200)
  2180. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2181. # self.setStyleSheet(
  2182. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2183. # "background-attachment: fixed"
  2184. # )
  2185. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2186. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2187. # palette = QtGui.QPalette()
  2188. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2189. # self.setPalette(palette)
  2190. logo = QtWidgets.QLabel()
  2191. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2192. title = QtWidgets.QLabel(
  2193. "<font size=8><B>FlatCAM</B></font><BR>"
  2194. "{title}<BR>"
  2195. "<BR>"
  2196. "<BR>"
  2197. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2198. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2199. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2200. "<B>{issue}</B></a><BR>".format(
  2201. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2202. devel=_("Development"),
  2203. down=_("DOWNLOAD"),
  2204. issue=_("Issue tracker"))
  2205. )
  2206. title.setOpenExternalLinks(True)
  2207. closebtn = QtWidgets.QPushButton(_("Close"))
  2208. tab_widget = QtWidgets.QTabWidget()
  2209. description_label = QtWidgets.QLabel(
  2210. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2211. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2212. version=version,
  2213. beta=('BETA' if beta else ''),
  2214. date=version_date,
  2215. arch=platform.architecture()[0])
  2216. )
  2217. description_label.setOpenExternalLinks(True)
  2218. lic_lbl_header = QtWidgets.QLabel(
  2219. '%s:<br>%s<br>' % (
  2220. _('Licensed under the MIT license'),
  2221. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2222. "http://www.opensource.org/licenses/mit-license.php</a>"
  2223. )
  2224. )
  2225. lic_lbl_header.setOpenExternalLinks(True)
  2226. lic_lbl_body = QtWidgets.QLabel(
  2227. _(
  2228. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2229. 'of this software and associated documentation files (the "Software"), to deal\n'
  2230. 'in the Software without restriction, including without limitation the rights\n'
  2231. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2232. 'copies of the Software, and to permit persons to whom the Software is\n'
  2233. 'furnished to do so, subject to the following conditions:\n\n'
  2234. 'The above copyright notice and this permission notice shall be included in\n'
  2235. 'all copies or substantial portions of the Software.\n\n'
  2236. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2237. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2238. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2239. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2240. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2241. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2242. 'THE SOFTWARE.'
  2243. )
  2244. )
  2245. attributions_label = QtWidgets.QLabel(
  2246. _(
  2247. 'Some of the icons used are from the following sources:<br>'
  2248. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2249. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2250. 'title="Flaticon">www.flaticon.com</a></div>'
  2251. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2252. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2253. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2254. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2255. 'title="Flaticon">www.flaticon.com</a></div>'
  2256. )
  2257. )
  2258. attributions_label.setOpenExternalLinks(True)
  2259. # layouts
  2260. layout1 = QtWidgets.QVBoxLayout()
  2261. layout1_1 = QtWidgets.QHBoxLayout()
  2262. layout1_2 = QtWidgets.QHBoxLayout()
  2263. layout2 = QtWidgets.QHBoxLayout()
  2264. layout3 = QtWidgets.QHBoxLayout()
  2265. self.setLayout(layout1)
  2266. layout1.addLayout(layout1_1)
  2267. layout1.addLayout(layout1_2)
  2268. layout1.addLayout(layout2)
  2269. layout1.addLayout(layout3)
  2270. layout1_1.addStretch()
  2271. layout1_1.addWidget(description_label)
  2272. layout1_2.addWidget(tab_widget)
  2273. self.splash_tab = QtWidgets.QWidget()
  2274. self.splash_tab.setObjectName("splash_about")
  2275. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2276. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2277. tab_widget.addTab(self.splash_tab, _("Splash"))
  2278. self.programmmers_tab = QtWidgets.QWidget()
  2279. self.programmmers_tab.setObjectName("programmers_about")
  2280. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2281. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2282. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2283. self.translators_tab = QtWidgets.QWidget()
  2284. self.translators_tab.setObjectName("translators_about")
  2285. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2286. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2287. tab_widget.addTab(self.translators_tab, _("Translators"))
  2288. self.license_tab = QtWidgets.QWidget()
  2289. self.license_tab.setObjectName("license_about")
  2290. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2291. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2292. tab_widget.addTab(self.license_tab, _("License"))
  2293. self.attributions_tab = QtWidgets.QWidget()
  2294. self.attributions_tab.setObjectName("attributions_about")
  2295. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2296. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2297. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2298. self.splash_tab_layout.addWidget(logo, stretch=0)
  2299. self.splash_tab_layout.addWidget(title, stretch=1)
  2300. pal = QtGui.QPalette()
  2301. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2302. self.prog_grid_lay = QtWidgets.QGridLayout()
  2303. self.prog_grid_lay.setHorizontalSpacing(20)
  2304. self.prog_grid_lay.setColumnStretch(0, 0)
  2305. self.prog_grid_lay.setColumnStretch(2, 1)
  2306. prog_widget = QtWidgets.QWidget()
  2307. prog_widget.setLayout(self.prog_grid_lay)
  2308. prog_scroll = QtWidgets.QScrollArea()
  2309. prog_scroll.setWidget(prog_widget)
  2310. prog_scroll.setWidgetResizable(True)
  2311. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2312. prog_scroll.setPalette(pal)
  2313. self.programmmers_tab_layout.addWidget(prog_scroll)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2361. self.translator_grid_lay = QtWidgets.QGridLayout()
  2362. self.translator_grid_lay.setColumnStretch(0, 0)
  2363. self.translator_grid_lay.setColumnStretch(1, 0)
  2364. self.translator_grid_lay.setColumnStretch(2, 1)
  2365. self.translator_grid_lay.setColumnStretch(3, 0)
  2366. # trans_widget = QtWidgets.QWidget()
  2367. # trans_widget.setLayout(self.translator_grid_lay)
  2368. # self.translators_tab_layout.addWidget(trans_widget)
  2369. # self.translators_tab_layout.addStretch()
  2370. trans_widget = QtWidgets.QWidget()
  2371. trans_widget.setLayout(self.translator_grid_lay)
  2372. trans_scroll = QtWidgets.QScrollArea()
  2373. trans_scroll.setWidget(trans_widget)
  2374. trans_scroll.setWidgetResizable(True)
  2375. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2376. trans_scroll.setPalette(pal)
  2377. self.translators_tab_layout.addWidget(trans_scroll)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2404. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2405. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2406. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2407. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2408. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2409. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2411. self.translator_grid_lay.setColumnStretch(0, 0)
  2412. self.translators_tab_layout.addStretch()
  2413. self.license_tab_layout.addWidget(lic_lbl_header)
  2414. self.license_tab_layout.addWidget(lic_lbl_body)
  2415. self.license_tab_layout.addStretch()
  2416. self.attributions_tab_layout.addWidget(attributions_label)
  2417. self.attributions_tab_layout.addStretch()
  2418. layout3.addStretch()
  2419. layout3.addWidget(closebtn)
  2420. closebtn.clicked.connect(self.accept)
  2421. AboutDialog(app=self, parent=self.ui).exec_()
  2422. def on_readme(self):
  2423. """
  2424. Displays the "about" dialog found in the Menu --> Help.
  2425. :return: None
  2426. """
  2427. class ReadmeDialog(QtWidgets.QDialog):
  2428. def __init__(self, app, parent=None):
  2429. QtWidgets.QDialog.__init__(self, parent)
  2430. self.app = app
  2431. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2432. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2433. "<b>click</b></a>"
  2434. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2435. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2436. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2437. # Icon and title
  2438. self.setWindowIcon(parent.app_icon)
  2439. self.setWindowTitle(_("Important Information's"))
  2440. self.resize(750, 375)
  2441. logo = QtWidgets.QLabel()
  2442. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2443. content = QtWidgets.QLabel(
  2444. "%s<br>"
  2445. "%s<br><br>"
  2446. "%s,<br>"
  2447. "%s<br>"
  2448. "<ul>"
  2449. "<li> &nbsp;%s %s</li>"
  2450. "<li> &nbsp;%s %s</li>"
  2451. "</ul>"
  2452. "%s %s.<br>"
  2453. "%s"
  2454. "<ul>"
  2455. "<li> &nbsp;%s &#128077;</li>"
  2456. "<li> &nbsp;%s &#128513;</li>"
  2457. "</ul>" %
  2458. (
  2459. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2460. _("Yet it cannot evolve without <b>contributions</b>."),
  2461. _("If you want to see this application grow and become better and better"),
  2462. _("you can <b>contribute</b> to the development yourself by:"),
  2463. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2464. new_features_link,
  2465. _("Bug Reports by providing the steps required to reproduce the bug"),
  2466. bugs_link,
  2467. _("If you like or use this program you can make a donation"),
  2468. donation_link,
  2469. _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2470. _("it will be welcomed with joy"),
  2471. _("it will give me a reason to continue")
  2472. )
  2473. )
  2474. content.setOpenExternalLinks(True)
  2475. # palette
  2476. pal = QtGui.QPalette()
  2477. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2478. # layouts
  2479. main_layout = QtWidgets.QVBoxLayout()
  2480. self.setLayout(main_layout)
  2481. tab_layout = QtWidgets.QHBoxLayout()
  2482. buttons_hlay = QtWidgets.QHBoxLayout()
  2483. main_layout.addLayout(tab_layout)
  2484. main_layout.addLayout(buttons_hlay)
  2485. tab_widget = QtWidgets.QTabWidget()
  2486. tab_layout.addWidget(tab_widget)
  2487. closebtn = QtWidgets.QPushButton(_("Close"))
  2488. buttons_hlay.addStretch()
  2489. buttons_hlay.addWidget(closebtn)
  2490. # CONTRIBUTE section
  2491. self.intro_tab = QtWidgets.QWidget()
  2492. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2493. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2494. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2495. self.grid_lay = QtWidgets.QGridLayout()
  2496. self.grid_lay.setHorizontalSpacing(20)
  2497. self.grid_lay.setColumnStretch(0, 0)
  2498. self.grid_lay.setColumnStretch(1, 1)
  2499. intro_wdg = QtWidgets.QWidget()
  2500. intro_wdg.setLayout(self.grid_lay)
  2501. intro_scroll_area = QtWidgets.QScrollArea()
  2502. intro_scroll_area.setWidget(intro_wdg)
  2503. intro_scroll_area.setWidgetResizable(True)
  2504. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2505. intro_scroll_area.setPalette(pal)
  2506. self.grid_lay.addWidget(logo, 0, 0)
  2507. self.grid_lay.addWidget(content, 0, 1)
  2508. self.intro_tab_layout.addWidget(intro_scroll_area)
  2509. # LINKS EXCHANGE section
  2510. self.links_tab = QtWidgets.QWidget()
  2511. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2512. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2513. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2514. self.links_lay = QtWidgets.QHBoxLayout()
  2515. links_wdg = QtWidgets.QWidget()
  2516. links_wdg.setLayout(self.links_lay)
  2517. links_scroll_area = QtWidgets.QScrollArea()
  2518. links_scroll_area.setWidget(links_wdg)
  2519. links_scroll_area.setWidgetResizable(True)
  2520. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2521. links_scroll_area.setPalette(pal)
  2522. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2523. self.links_tab_layout.addWidget(links_scroll_area)
  2524. # HOW TO section
  2525. self.howto_tab = QtWidgets.QWidget()
  2526. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2527. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2528. tab_widget.addTab(self.howto_tab, _("How To's"))
  2529. self.howto_lay = QtWidgets.QHBoxLayout()
  2530. howto_wdg = QtWidgets.QWidget()
  2531. howto_wdg.setLayout(self.howto_lay)
  2532. howto_scroll_area = QtWidgets.QScrollArea()
  2533. howto_scroll_area.setWidget(howto_wdg)
  2534. howto_scroll_area.setWidgetResizable(True)
  2535. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2536. howto_scroll_area.setPalette(pal)
  2537. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2538. self.howto_tab_layout.addWidget(howto_scroll_area)
  2539. # BUTTONS section
  2540. closebtn.clicked.connect(self.accept)
  2541. ReadmeDialog(app=self, parent=self.ui).exec_()
  2542. def install_bookmarks(self, book_dict=None):
  2543. """
  2544. Install the bookmarks actions in the Help menu -> Bookmarks
  2545. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2546. :return: None
  2547. """
  2548. if book_dict is None:
  2549. self.defaults["global_bookmarks"].update(
  2550. {
  2551. '1': ['FlatCAM', "http://flatcam.org"],
  2552. '2': ['Backup Site', ""]
  2553. }
  2554. )
  2555. else:
  2556. self.defaults["global_bookmarks"].clear()
  2557. self.defaults["global_bookmarks"].update(book_dict)
  2558. # first try to disconnect if somehow they get connected from elsewhere
  2559. for act in self.ui.menuhelp_bookmarks.actions():
  2560. try:
  2561. act.triggered.disconnect()
  2562. except TypeError:
  2563. pass
  2564. # clear all actions except the last one who is the Bookmark manager
  2565. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2566. pass
  2567. else:
  2568. self.ui.menuhelp_bookmarks.removeAction(act)
  2569. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2570. if self.defaults["global_bookmarks"]:
  2571. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2572. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2573. # the JSON is first making the keys as strings (therefore I have to use strings too
  2574. # or do the conversion :(
  2575. # )
  2576. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2577. # the '10' entry jsut after '1' therefore ordering as strings
  2578. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2579. key=lambda x: int(x[0]))
  2580. for entry, bookmark in sorted_bookmarks:
  2581. title = bookmark[0]
  2582. weblink = bookmark[1]
  2583. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2584. act.setText(title)
  2585. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2586. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2587. if title == 'Backup Site' and weblink == "":
  2588. act.triggered.connect(self.on_backup_site)
  2589. else:
  2590. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2591. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2592. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2593. def on_bookmarks_manager(self):
  2594. """
  2595. Adds the bookmark manager in a Tab in Plot Area
  2596. :return:
  2597. """
  2598. for idx in range(self.ui.plot_tab_area.count()):
  2599. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2600. # there can be only one instance of Bookmark Manager at one time
  2601. return
  2602. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2603. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2604. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2605. # add the tab if it was closed
  2606. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2607. # delete the absolute and relative position and messages in the infobar
  2608. self.ui.position_label.setText("")
  2609. # self.ui.rel_position_label.setText("")
  2610. # Switch plot_area to preferences page
  2611. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2612. def on_backup_site(self):
  2613. msgbox = QtWidgets.QMessageBox()
  2614. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2615. "1. FlatCAM.org website is down\n"
  2616. "2. Someone forked FlatCAM project and wants to point\n"
  2617. "to his own website\n\n"
  2618. "If you can't get any informations about FlatCAM beta\n"
  2619. "use the YouTube channel link from the Help menu."))
  2620. msgbox.setWindowTitle(_("Alternative website"))
  2621. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2622. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2623. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2624. msgbox.setDefaultButton(bt_yes)
  2625. msgbox.exec_()
  2626. # response = msgbox.clickedButton()
  2627. def on_file_savedefaults(self):
  2628. """
  2629. Callback for menu item File->Save Defaults. Saves application default options
  2630. ``self.defaults`` to current_defaults.FlatConfig.
  2631. :return: None
  2632. """
  2633. self.preferencesUiManager.save_defaults()
  2634. def final_save(self):
  2635. """
  2636. Callback for doing a preferences save to file whenever the application is about to quit.
  2637. If the project has changes, it will ask the user to save the project.
  2638. :return: None
  2639. """
  2640. if self.save_in_progress:
  2641. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2642. return
  2643. if self.should_we_save and self.collection.get_list():
  2644. msgbox = QtWidgets.QMessageBox()
  2645. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2646. "\n"
  2647. "Do you want to Save the project?"))
  2648. msgbox.setWindowTitle(_("Save changes"))
  2649. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2650. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2651. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2652. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2653. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2654. msgbox.setDefaultButton(bt_yes)
  2655. msgbox.exec_()
  2656. response = msgbox.clickedButton()
  2657. if response == bt_yes:
  2658. try:
  2659. self.trayIcon.hide()
  2660. except Exception:
  2661. pass
  2662. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2663. elif response == bt_no:
  2664. try:
  2665. self.trayIcon.hide()
  2666. except Exception:
  2667. pass
  2668. self.quit_application()
  2669. elif response == bt_cancel:
  2670. return
  2671. else:
  2672. try:
  2673. self.trayIcon.hide()
  2674. except Exception:
  2675. pass
  2676. self.quit_application()
  2677. def quit_application(self):
  2678. """
  2679. Called (as a pyslot or not) when the application is quit.
  2680. :return: None
  2681. """
  2682. # close editors before quiting the app, if they are open
  2683. if self.geo_editor.editor_active is True:
  2684. self.geo_editor.deactivate()
  2685. try:
  2686. self.geo_editor.disconnect()
  2687. except TypeError:
  2688. pass
  2689. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2690. if self.exc_editor.editor_active is True:
  2691. self.exc_editor.deactivate()
  2692. try:
  2693. self.grb_editor.disconnect()
  2694. except TypeError:
  2695. pass
  2696. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2697. if self.grb_editor.editor_active is True:
  2698. self.grb_editor.deactivate_grb_editor()
  2699. try:
  2700. self.exc_editor.disconnect()
  2701. except TypeError:
  2702. pass
  2703. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2704. # disconnect the mouse events
  2705. if self.is_legacy:
  2706. self.plotcanvas.graph_event_disconnect(self.mm)
  2707. self.plotcanvas.graph_event_disconnect(self.mp)
  2708. self.plotcanvas.graph_event_disconnect(self.mr)
  2709. self.plotcanvas.graph_event_disconnect(self.mdc)
  2710. self.plotcanvas.graph_event_disconnect(self.kp)
  2711. else:
  2712. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2713. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2714. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2715. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2716. self.on_mouse_double_click_over_plot)
  2717. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2718. self.preferencesUiManager.save_defaults(silent=True)
  2719. log.debug("App.quit_application() --> App Defaults saved.")
  2720. if self.cmd_line_headless != 1:
  2721. # save app state to file
  2722. stgs = QSettings("Open Source", "FlatCAM")
  2723. stgs.setValue('saved_gui_state', self.ui.saveState())
  2724. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2725. stgs.setValue(
  2726. 'language',
  2727. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2728. )
  2729. stgs.setValue(
  2730. 'notebook_font_size',
  2731. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2732. )
  2733. stgs.setValue(
  2734. 'axis_font_size',
  2735. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2736. )
  2737. stgs.setValue(
  2738. 'textbox_font_size',
  2739. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2740. )
  2741. stgs.setValue(
  2742. 'hud_font_size',
  2743. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2744. )
  2745. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2746. stgs.setValue(
  2747. 'machinist',
  2748. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2749. )
  2750. # This will write the setting to the platform specific storage.
  2751. del stgs
  2752. log.debug("App.quit_application() --> App UI state saved.")
  2753. # try to quit the Socket opened by ArgsThread class
  2754. try:
  2755. # self.new_launch.thread_exit = True
  2756. # self.new_launch.listener.close()
  2757. self.new_launch.stop.emit()
  2758. except Exception as err:
  2759. log.debug("App.quit_application() --> %s" % str(err))
  2760. # try to quit the QThread that run ArgsThread class
  2761. try:
  2762. # del self.new_launch
  2763. self.listen_th.quit()
  2764. except Exception as e:
  2765. log.debug("App.quit_application() --> %s" % str(e))
  2766. # terminate workers
  2767. # self.workers.__del__()
  2768. self.clear_pool()
  2769. # quit app by signalling for self.kill_app() method
  2770. # self.close_app_signal.emit()
  2771. QtWidgets.qApp.quit()
  2772. # QtCore.QCoreApplication.quit()
  2773. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2774. # we use the following command
  2775. # minor_v = sys.version_info.minor
  2776. # if minor_v < 8:
  2777. # # make sure that the app closes
  2778. # sys.exit(0)
  2779. # else:
  2780. # os._exit(0) # fix to work with Python 3.8
  2781. @staticmethod
  2782. def kill_app():
  2783. QtWidgets.qApp.quit()
  2784. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2785. # we use the following command
  2786. sys.exit(0)
  2787. def on_portable_checked(self, state):
  2788. """
  2789. Callback called when the checkbox in Preferences GUI is checked.
  2790. It will set the application as portable by creating the preferences and recent files in the
  2791. 'config' folder found in the FlatCAM installation folder.
  2792. :param state: boolean, the state of the checkbox when clicked/checked
  2793. :return:
  2794. """
  2795. line_no = 0
  2796. data = None
  2797. if sys.platform != 'win32':
  2798. # this won't work in Linux or MacOS
  2799. return
  2800. # test if the app was frozen and choose the path for the configuration file
  2801. if getattr(sys, "frozen", False) is True:
  2802. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2803. else:
  2804. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2805. config_file = current_data_path + '\\configuration.txt'
  2806. try:
  2807. with open(config_file, 'r') as f:
  2808. try:
  2809. data = f.readlines()
  2810. except Exception as e:
  2811. log.debug('App.__init__() -->%s' % str(e))
  2812. return
  2813. except FileNotFoundError:
  2814. pass
  2815. for line in data:
  2816. line = line.strip('\n')
  2817. param = str(line).rpartition('=')
  2818. if param[0] == 'portable':
  2819. break
  2820. line_no += 1
  2821. if state:
  2822. data[line_no] = 'portable=True\n'
  2823. # create the new defauults files
  2824. # create current_defaults.FlatConfig file if there is none
  2825. try:
  2826. f = open(current_data_path + '/current_defaults.FlatConfig')
  2827. f.close()
  2828. except IOError:
  2829. App.log.debug('Creating empty current_defaults.FlatConfig')
  2830. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2831. json.dump({}, f)
  2832. f.close()
  2833. # create factory_defaults.FlatConfig file if there is none
  2834. try:
  2835. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2836. f.close()
  2837. except IOError:
  2838. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2839. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2840. json.dump({}, f)
  2841. f.close()
  2842. try:
  2843. f = open(current_data_path + '/recent.json')
  2844. f.close()
  2845. except IOError:
  2846. App.log.debug('Creating empty recent.json')
  2847. f = open(current_data_path + '/recent.json', 'w')
  2848. json.dump([], f)
  2849. f.close()
  2850. try:
  2851. fp = open(current_data_path + '/recent_projects.json')
  2852. fp.close()
  2853. except IOError:
  2854. App.log.debug('Creating empty recent_projects.json')
  2855. fp = open(current_data_path + '/recent_projects.json', 'w')
  2856. json.dump([], fp)
  2857. fp.close()
  2858. # save the current defaults to the new defaults file
  2859. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2860. else:
  2861. data[line_no] = 'portable=False\n'
  2862. with open(config_file, 'w') as f:
  2863. f.writelines(data)
  2864. def on_register_files(self, obj_type=None):
  2865. """
  2866. Called whenever there is a need to register file extensions with FlatCAM.
  2867. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2868. :param obj_type: the type of object to be register for.
  2869. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2870. :return: None
  2871. """
  2872. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2873. new_reg_path = 'Software\\Classes\\'
  2874. # find if the current user is admin
  2875. try:
  2876. is_admin = os.getuid() == 0
  2877. except AttributeError:
  2878. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2879. if is_admin is True:
  2880. root_path = winreg.HKEY_LOCAL_MACHINE
  2881. else:
  2882. root_path = winreg.HKEY_CURRENT_USER
  2883. # create the keys
  2884. def set_reg(name, root_pth, new_reg_path, value):
  2885. try:
  2886. winreg.CreateKey(root_pth, new_reg_path)
  2887. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2888. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2889. return True
  2890. except WindowsError:
  2891. return False
  2892. # delete key in registry
  2893. def delete_reg(root_pth, reg_path, key_to_del):
  2894. key_to_del_path = reg_path + key_to_del
  2895. try:
  2896. winreg.DeleteKey(root_pth, key_to_del_path)
  2897. return True
  2898. except WindowsError:
  2899. return False
  2900. if obj_type is None or obj_type == 'excellon':
  2901. exc_list = \
  2902. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2903. exc_list = [x for x in exc_list if x != '']
  2904. # register all keys in the Preferences window
  2905. for ext in exc_list:
  2906. new_k = new_reg_path + '.%s' % ext
  2907. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2908. # and unregister those that are no longer in the Preferences windows but are in the file
  2909. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2910. if ext not in exc_list:
  2911. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2912. # now write the updated extensions to the self.defaults
  2913. # new_ext = ''
  2914. # for ext in exc_list:
  2915. # new_ext = new_ext + ext + ', '
  2916. # self.defaults["fa_excellon"] = new_ext
  2917. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2918. if obj_type is None or obj_type == 'gcode':
  2919. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2920. gco_list = [x for x in gco_list if x != '']
  2921. # register all keys in the Preferences window
  2922. for ext in gco_list:
  2923. new_k = new_reg_path + '.%s' % ext
  2924. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2925. # and unregister those that are no longer in the Preferences windows but are in the file
  2926. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2927. if ext not in gco_list:
  2928. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2929. # now write the updated extensions to the self.defaults
  2930. # new_ext = ''
  2931. # for ext in gco_list:
  2932. # new_ext = new_ext + ext + ', '
  2933. # self.defaults["fa_gcode"] = new_ext
  2934. self.inform.emit('[success] %s' %
  2935. _("Selected GCode file extensions registered with FlatCAM."))
  2936. if obj_type is None or obj_type == 'gerber':
  2937. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2938. grb_list = [x for x in grb_list if x != '']
  2939. # register all keys in the Preferences window
  2940. for ext in grb_list:
  2941. new_k = new_reg_path + '.%s' % ext
  2942. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2943. # and unregister those that are no longer in the Preferences windows but are in the file
  2944. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2945. if ext not in grb_list:
  2946. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2947. # now write the updated extensions to the self.defaults
  2948. # new_ext = ''
  2949. # for ext in grb_list:
  2950. # new_ext = new_ext + ext + ', '
  2951. # self.defaults["fa_gerber"] = new_ext
  2952. self.inform.emit('[success] %s' %
  2953. _("Selected Gerber file extensions registered with FlatCAM."))
  2954. def add_extension(self, ext_type):
  2955. """
  2956. Add a file extension to the list for a specific object
  2957. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2958. :return:
  2959. """
  2960. if ext_type == 'excellon':
  2961. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2962. if new_ext == '':
  2963. return
  2964. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2965. if new_ext in old_val:
  2966. return
  2967. old_val.append(new_ext)
  2968. old_val.sort()
  2969. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2970. if ext_type == 'gcode':
  2971. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2972. if new_ext == '':
  2973. return
  2974. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2975. if new_ext in old_val:
  2976. return
  2977. old_val.append(new_ext)
  2978. old_val.sort()
  2979. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2980. if ext_type == 'gerber':
  2981. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2982. if new_ext == '':
  2983. return
  2984. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2985. if new_ext in old_val:
  2986. return
  2987. old_val.append(new_ext)
  2988. old_val.sort()
  2989. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2990. if ext_type == 'keyword':
  2991. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2992. if new_kw == '':
  2993. return
  2994. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2995. if new_kw in old_val:
  2996. return
  2997. old_val.append(new_kw)
  2998. old_val.sort()
  2999. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3000. # update the self.myKeywords so the model is updated
  3001. self.autocomplete_kw_list = \
  3002. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3003. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3004. self.shell._edit.set_model_data(self.myKeywords)
  3005. def del_extension(self, ext_type):
  3006. """
  3007. Remove a file extension from the list for a specific object
  3008. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3009. :return:
  3010. """
  3011. if ext_type == 'excellon':
  3012. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3013. if new_ext == '':
  3014. return
  3015. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3016. if new_ext not in old_val:
  3017. return
  3018. old_val.remove(new_ext)
  3019. old_val.sort()
  3020. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3021. if ext_type == 'gcode':
  3022. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3023. if new_ext == '':
  3024. return
  3025. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3026. if new_ext not in old_val:
  3027. return
  3028. old_val.remove(new_ext)
  3029. old_val.sort()
  3030. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3031. if ext_type == 'gerber':
  3032. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3033. if new_ext == '':
  3034. return
  3035. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3036. if new_ext not in old_val:
  3037. return
  3038. old_val.remove(new_ext)
  3039. old_val.sort()
  3040. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3041. if ext_type == 'keyword':
  3042. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3043. if new_kw == '':
  3044. return
  3045. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3046. if new_kw not in old_val:
  3047. return
  3048. old_val.remove(new_kw)
  3049. old_val.sort()
  3050. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3051. # update the self.myKeywords so the model is updated
  3052. self.autocomplete_kw_list = \
  3053. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3054. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3055. self.shell._edit.set_model_data(self.myKeywords)
  3056. def restore_extensions(self, ext_type):
  3057. """
  3058. Restore all file extensions associations with FlatCAM, for a specific object
  3059. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3060. :return:
  3061. """
  3062. if ext_type == 'excellon':
  3063. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3064. # for the ability to open Excellon files with .txt extension
  3065. new_exc_list = deepcopy(self.exc_list)
  3066. try:
  3067. new_exc_list.remove('txt')
  3068. except ValueError:
  3069. pass
  3070. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3071. if ext_type == 'gcode':
  3072. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3073. if ext_type == 'gerber':
  3074. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3075. if ext_type == 'keyword':
  3076. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3077. # update the self.myKeywords so the model is updated
  3078. self.autocomplete_kw_list = self.default_keywords
  3079. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3080. self.shell._edit.set_model_data(self.myKeywords)
  3081. def delete_all_extensions(self, ext_type):
  3082. """
  3083. Delete all file extensions associations with FlatCAM, for a specific object
  3084. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3085. :return:
  3086. """
  3087. if ext_type == 'excellon':
  3088. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3089. if ext_type == 'gcode':
  3090. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3091. if ext_type == 'gerber':
  3092. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3093. if ext_type == 'keyword':
  3094. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3095. # update the self.myKeywords so the model is updated
  3096. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3097. self.shell._edit.set_model_data(self.myKeywords)
  3098. def on_edit_join(self, name=None):
  3099. """
  3100. Callback for Edit->Join. Joins the selected geometry objects into
  3101. a new one.
  3102. :return: None
  3103. """
  3104. self.defaults.report_usage("on_edit_join()")
  3105. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3106. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3107. geo_type_set = set()
  3108. objs = self.collection.get_selected()
  3109. if len(objs) < 2:
  3110. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3111. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3112. return 'fail'
  3113. for obj in objs:
  3114. geo_type_set.add(obj.multigeo)
  3115. # if len(geo_type_list) == 1 means that all list elements are the same
  3116. if len(geo_type_set) != 1:
  3117. self.inform.emit('[ERROR] %s' %
  3118. _("Failed join. The Geometry objects are of different types.\n"
  3119. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3120. "convert from one to another and retry joining \n"
  3121. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3122. "the result may not be what was expected. \n"
  3123. "Check the generated GCODE."))
  3124. return
  3125. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3126. if True in geo_type_set:
  3127. def initialize(geo_obj, app):
  3128. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3129. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3130. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3131. for v in geo_obj.tools.values():
  3132. v['data']['name'] = obj_name_multi
  3133. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3134. else:
  3135. def initialize(geo_obj, app):
  3136. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3137. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3138. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3139. for v in geo_obj.tools.values():
  3140. v['data']['name'] = obj_name_single
  3141. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3142. self.should_we_save = True
  3143. def on_edit_join_exc(self):
  3144. """
  3145. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3146. a new Excellon.
  3147. :return: None
  3148. """
  3149. self.defaults.report_usage("on_edit_join_exc()")
  3150. objs = self.collection.get_selected()
  3151. for obj in objs:
  3152. if not isinstance(obj, ExcellonObject):
  3153. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3154. return
  3155. if len(objs) < 2:
  3156. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3157. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3158. return 'fail'
  3159. def initialize(exc_obj, app):
  3160. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3161. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3162. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3163. self.should_we_save = True
  3164. def on_edit_join_grb(self):
  3165. """
  3166. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3167. a new Gerber object.
  3168. :return: None
  3169. """
  3170. self.defaults.report_usage("on_edit_join_grb()")
  3171. objs = self.collection.get_selected()
  3172. for obj in objs:
  3173. if not isinstance(obj, GerberObject):
  3174. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3175. return
  3176. if len(objs) < 2:
  3177. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3178. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3179. return 'fail'
  3180. def initialize(grb_obj, app):
  3181. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3182. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3183. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3184. self.should_we_save = True
  3185. def on_convert_singlegeo_to_multigeo(self):
  3186. """
  3187. Called for converting a Geometry object from single-geo to multi-geo.
  3188. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3189. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3190. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3191. the solid-geometry of that tool.
  3192. :return: None
  3193. """
  3194. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3195. obj = self.collection.get_active()
  3196. if obj is None:
  3197. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3198. return
  3199. if not isinstance(obj, GeometryObject):
  3200. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3201. return
  3202. obj.multigeo = True
  3203. for tooluid, dict_value in obj.tools.items():
  3204. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3205. if not isinstance(obj.solid_geometry, list):
  3206. obj.solid_geometry = [obj.solid_geometry]
  3207. # obj.solid_geometry[:] = []
  3208. obj.plot()
  3209. self.should_we_save = True
  3210. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3211. def on_convert_multigeo_to_singlegeo(self):
  3212. """
  3213. Called for converting a Geometry object from multi-geo to single-geo.
  3214. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3215. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3216. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3217. the solid-geometry of that tool.
  3218. :return: None
  3219. """
  3220. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3221. obj = self.collection.get_active()
  3222. if obj is None:
  3223. self.inform.emit('[ERROR_NOTCL] %s' %
  3224. _("Failed. Select a Geometry Object and try again."))
  3225. return
  3226. if not isinstance(obj, GeometryObject):
  3227. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3228. (_("Expected a GeometryObject, got"), type(obj)))
  3229. return
  3230. obj.multigeo = False
  3231. total_solid_geometry = []
  3232. for tooluid, dict_value in obj.tools.items():
  3233. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3234. # clear the original geometry
  3235. dict_value['solid_geometry'][:] = []
  3236. obj.solid_geometry = deepcopy(total_solid_geometry)
  3237. obj.plot()
  3238. self.should_we_save = True
  3239. self.inform.emit('[success] %s' %
  3240. _("A Geometry object was converted to SingleGeo type."))
  3241. def on_defaults_dict_change(self, field):
  3242. """
  3243. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3244. Edit -> Preferences tab window.
  3245. :param field: the key of the self.defaults dictionary that was changed.
  3246. :return: None
  3247. """
  3248. self.preferencesUiManager.defaults_write_form_field(field=field)
  3249. if field == "units":
  3250. self.set_screen_units(self.defaults['units'])
  3251. def set_screen_units(self, units):
  3252. """
  3253. Set the FlatCAM units on the status bar.
  3254. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3255. :return: None
  3256. """
  3257. self.ui.units_label.setText("[" + units.lower() + "]")
  3258. def on_toggle_units_click(self):
  3259. try:
  3260. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3261. except (TypeError, AttributeError):
  3262. pass
  3263. if self.defaults["units"] == 'MM':
  3264. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3265. else:
  3266. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3267. self.on_toggle_units(no_pref=True)
  3268. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3269. lambda: self.on_toggle_units(no_pref=False))
  3270. def on_toggle_units(self, no_pref=False):
  3271. """
  3272. Callback for the Units radio-button change in the Preferences tab.
  3273. Changes the application's default units adn for the project too.
  3274. If changing the project's units, the change propagates to all of
  3275. the objects in the project.
  3276. :return: None
  3277. """
  3278. self.defaults.report_usage("on_toggle_units")
  3279. if self.toggle_units_ignore:
  3280. return
  3281. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3282. # If option is the same, then ignore
  3283. if new_units == self.defaults["units"].upper():
  3284. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3285. return
  3286. # Keys in self.defaults for which to scale their values
  3287. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3288. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3289. "tools_iso_tool_vtipdia",
  3290. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3291. "gerber_editor_ma_high",
  3292. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3293. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3294. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3295. "excellon_feedrate_probe", "excellon_milling_dia",
  3296. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3297. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3298. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3299. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3300. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3301. "geometry_extracut_length", "geometry_z_pdepth",
  3302. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3303. 'cncjob_tooldia',
  3304. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3305. "tools_paintnewdia",
  3306. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3307. "tools_nccnewdia", "tools_ncc_offset_value",
  3308. "tools_2sided_drilldia",
  3309. "tools_film_boundary", "tools_film_scale_stroke",
  3310. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3311. "tools_cutout_depthperpass",
  3312. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3313. "tools_panelize_spacing_rows",
  3314. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3315. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3316. "tools_transform_buffer_dis",
  3317. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3318. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3319. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3320. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3321. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3322. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3323. "tools_cr_h2h_val", "tools_cr_dh_val",
  3324. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3325. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3326. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3327. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3328. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3329. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3330. "tools_copper_thieving_mask_clearance",
  3331. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3332. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3333. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3334. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3335. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3336. "tools_invert_margin",
  3337. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3338. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3339. def scale_defaults(sfactor):
  3340. for dim in dimensions:
  3341. if dim in [
  3342. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3343. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3344. 'tools_transform_mirror_point'
  3345. ]:
  3346. if self.defaults[dim] is None or self.defaults[dim] == '':
  3347. continue
  3348. try:
  3349. coordinates = self.defaults[dim].split(",")
  3350. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3351. coords_xy[0] *= sfactor
  3352. coords_xy[1] *= sfactor
  3353. self.defaults[dim] = "%.*f, %.*f" % (
  3354. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3355. except Exception as e:
  3356. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3357. elif dim in [
  3358. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3359. ]:
  3360. if self.defaults[dim] is None or self.defaults[dim] == '':
  3361. continue
  3362. try:
  3363. self.defaults[dim] = float(self.defaults[dim])
  3364. tools_diameters = [self.defaults[dim]]
  3365. except ValueError:
  3366. try:
  3367. tools_string = self.defaults[dim].split(",")
  3368. tools_diameters = [eval(a) for a in tools_string if a != '']
  3369. except Exception as e:
  3370. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3371. continue
  3372. self.defaults[dim] = ''
  3373. td_len = len(tools_diameters)
  3374. if td_len > 1:
  3375. for t in range(td_len):
  3376. tools_diameters[t] *= sfactor
  3377. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3378. else:
  3379. tools_diameters[0] *= sfactor
  3380. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3381. elif dim in ['global_gridx', 'global_gridy']:
  3382. # format the number of decimals to the one specified in self.decimals
  3383. try:
  3384. val = float(self.defaults[dim]) * sfactor
  3385. except Exception as e:
  3386. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3387. continue
  3388. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3389. else:
  3390. # the number of decimals for the rest is kept unchanged
  3391. if self.defaults[dim]:
  3392. try:
  3393. val = float(self.defaults[dim]) * sfactor
  3394. except Exception as e:
  3395. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3396. continue
  3397. self.defaults[dim] = val
  3398. # The scaling factor depending on choice of units.
  3399. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3400. # Changing project units. Warn user.
  3401. msgbox = QtWidgets.QMessageBox()
  3402. msgbox.setWindowTitle(_("Toggle Units"))
  3403. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3404. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3405. msgbox.setText(_("Changing the units of the project\n"
  3406. "will scale all objects.\n\n"
  3407. "Do you want to continue?"))
  3408. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3409. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3410. msgbox.setDefaultButton(bt_ok)
  3411. msgbox.exec_()
  3412. response = msgbox.clickedButton()
  3413. if response == bt_ok:
  3414. if no_pref is False:
  3415. self.preferencesUiManager.defaults_read_form()
  3416. scale_defaults(factor)
  3417. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3418. self.defaults["units"] = new_units
  3419. # update the defaults from form, some may assume that the conversion is enough and it's not
  3420. self.on_options_app2project()
  3421. # update the objects
  3422. for obj in self.collection.get_list():
  3423. obj.convert_units(new_units)
  3424. # make that the properties stored in the object are also updated
  3425. self.app_obj.object_changed.emit(obj)
  3426. # rebuild the object UI
  3427. obj.build_ui()
  3428. # change this only if the workspace is active
  3429. if self.defaults['global_workspace'] is True:
  3430. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3431. # adjust the grid values on the main toolbar
  3432. val_x = float(self.defaults['global_gridx']) * factor
  3433. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3434. current = self.collection.get_active()
  3435. if current is not None:
  3436. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3437. if not isinstance(current, GeometryObject):
  3438. current.to_form()
  3439. # replot all objects
  3440. self.plot_all()
  3441. # set the status labels to reflect the current FlatCAM units
  3442. self.set_screen_units(new_units)
  3443. # signal to the app that we changed the object properties and it should save the project
  3444. self.should_we_save = True
  3445. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3446. else:
  3447. # Undo toggling
  3448. self.toggle_units_ignore = True
  3449. if self.defaults['units'].upper() == 'MM':
  3450. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3451. else:
  3452. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3453. self.toggle_units_ignore = False
  3454. # store the grid values so they are not changed in the next step
  3455. val_x = float(self.defaults['global_gridx'])
  3456. val_y = float(self.defaults['global_gridy'])
  3457. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3458. self.preferencesUiManager.defaults_read_form()
  3459. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3460. # in self.defaults from the GUI elements but
  3461. # I don't want it for the grid values, so I update them here
  3462. self.defaults['global_gridx'] = val_x
  3463. self.defaults['global_gridy'] = val_y
  3464. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3465. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3466. def on_tab_rmb_click(self, checked):
  3467. self.ui.notebook.set_detachable(val=checked)
  3468. self.defaults["global_tabs_detachable"] = checked
  3469. self.ui.plot_tab_area.set_detachable(val=checked)
  3470. self.defaults["global_tabs_detachable"] = checked
  3471. def on_tab_setup_context_menu(self):
  3472. initial_checked = self.defaults["global_tabs_detachable"]
  3473. action_name = str(_("Detachable Tabs"))
  3474. action = QtWidgets.QAction(self)
  3475. action.setCheckable(True)
  3476. action.setText(action_name)
  3477. action.setChecked(initial_checked)
  3478. self.ui.notebook.tabBar.addAction(action)
  3479. self.ui.plot_tab_area.tabBar.addAction(action)
  3480. try:
  3481. action.triggered.disconnect()
  3482. except TypeError:
  3483. pass
  3484. action.triggered.connect(self.on_tab_rmb_click)
  3485. def on_deselect_all(self):
  3486. self.collection.set_all_inactive()
  3487. self.delete_selection_shape()
  3488. def on_workspace_modified(self):
  3489. # self.save_defaults(silent=True)
  3490. self.plotcanvas.delete_workspace()
  3491. self.preferencesUiManager.defaults_read_form()
  3492. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3493. def on_workspace(self):
  3494. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3495. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3496. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3497. else:
  3498. self.plotcanvas.delete_workspace()
  3499. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3500. self.preferencesUiManager.defaults_read_form()
  3501. # self.save_defaults(silent=True)
  3502. def on_workspace_toggle(self):
  3503. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3504. try:
  3505. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3506. except TypeError:
  3507. pass
  3508. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3509. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3510. self.on_workspace()
  3511. def on_cursor_type(self, val):
  3512. """
  3513. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3514. :return: None
  3515. """
  3516. self.app_cursor.enabled = False
  3517. if val == 'small':
  3518. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3519. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3520. self.app_cursor = self.plotcanvas.new_cursor()
  3521. else:
  3522. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3523. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3524. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3525. if self.ui.grid_snap_btn.isChecked():
  3526. self.app_cursor.enabled = True
  3527. else:
  3528. self.app_cursor.enabled = False
  3529. def on_tool_add_keypress(self):
  3530. # ## Current application units in Upper Case
  3531. self.units = self.defaults['units'].upper()
  3532. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3533. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3534. if notebook_widget_name == 'selected_tab':
  3535. if self.collection.get_active().kind == 'geometry':
  3536. # Tool add works for Geometry only if Advanced is True in Preferences
  3537. if self.defaults["global_app_level"] == 'a':
  3538. tool_add_popup = FCInputDialog(title="New Tool ...",
  3539. text='Enter a Tool Diameter:',
  3540. min=0.0000, max=99.9999, decimals=4)
  3541. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3542. val, ok = tool_add_popup.get_value()
  3543. if ok:
  3544. if float(val) == 0:
  3545. self.inform.emit('[WARNING_NOTCL] %s' %
  3546. _("Please enter a tool diameter with non-zero value, in Float format."))
  3547. return
  3548. self.collection.get_active().on_tool_add(dia=float(val))
  3549. else:
  3550. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3551. else:
  3552. msgbox = QtWidgets.QMessageBox()
  3553. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3554. "Go to Preferences -> General - Show Advanced Options."))
  3555. msgbox.setWindowTitle("Tool adding ...")
  3556. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3557. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3558. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3559. msgbox.setDefaultButton(bt_ok)
  3560. msgbox.exec_()
  3561. # work only if the notebook tab on focus is the Tools_Tab
  3562. if notebook_widget_name == 'tool_tab':
  3563. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3564. # and only if the tool is NCC Tool
  3565. if tool_widget == self.ncclear_tool.toolName:
  3566. self.ncclear_tool.on_add_tool_by_key()
  3567. # and only if the tool is Paint Area Tool
  3568. elif tool_widget == self.paint_tool.toolName:
  3569. self.paint_tool.on_add_tool_by_key()
  3570. # and only if the tool is Solder Paste Dispensing Tool
  3571. elif tool_widget == self.paste_tool.toolName:
  3572. self.paste_tool.on_add_tool_by_key()
  3573. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3574. # See description below.
  3575. def on_delete_keypress(self):
  3576. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3577. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3578. if notebook_widget_name == 'selected_tab':
  3579. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3580. self.collection.get_active().on_tool_delete()
  3581. # work only if the notebook tab on focus is the Tools_Tab
  3582. elif notebook_widget_name == 'tool_tab':
  3583. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3584. # and only if the tool is NCC Tool
  3585. if tool_widget == self.ncclear_tool.toolName:
  3586. self.ncclear_tool.on_tool_delete()
  3587. # and only if the tool is Paint Tool
  3588. elif tool_widget == self.paint_tool.toolName:
  3589. self.paint_tool.on_tool_delete()
  3590. # and only if the tool is Solder Paste Dispensing Tool
  3591. elif tool_widget == self.paste_tool.toolName:
  3592. self.paste_tool.on_tool_delete()
  3593. # and only if the tool is Isolation Tool
  3594. elif tool_widget == self.isolation_tool.toolName:
  3595. self.isolation_tool.on_tool_delete()
  3596. else:
  3597. self.on_delete()
  3598. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3599. # some screens you have to be careful where you hover with your mouse.
  3600. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3601. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3602. # Complicated, I know :)
  3603. def on_delete(self, force_deletion=False):
  3604. """
  3605. Delete the currently selected FlatCAMObjs.
  3606. :param force_deletion: used by Tcl command
  3607. :return: None
  3608. """
  3609. self.defaults.report_usage("on_delete()")
  3610. response = None
  3611. bt_ok = None
  3612. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3613. # a geometry object before we update it.
  3614. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3615. and self.grb_editor.editor_active is False:
  3616. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3617. msgbox = QtWidgets.QMessageBox()
  3618. msgbox.setWindowTitle(_("Delete objects"))
  3619. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3620. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3621. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3622. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3623. "the selected objects?"))
  3624. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3625. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3626. msgbox.setDefaultButton(bt_ok)
  3627. msgbox.exec_()
  3628. response = msgbox.clickedButton()
  3629. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3630. response = bt_ok
  3631. if response == bt_ok:
  3632. if self.collection.get_active():
  3633. self.log.debug("App.on_delete()")
  3634. for obj_active in self.collection.get_selected():
  3635. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3636. if obj_active.kind == 'gerber':
  3637. for el in obj_active.mark_shapes:
  3638. obj_active.mark_shapes[el].clear(update=True)
  3639. obj_active.mark_shapes[el].enabled = False
  3640. # obj_active.mark_shapes[el] = None
  3641. del el
  3642. elif obj_active.kind == 'cncjob':
  3643. try:
  3644. obj_active.text_col.enabled = False
  3645. del obj_active.text_col
  3646. obj_active.annotation.clear(update=True)
  3647. del obj_active.annotation
  3648. except AttributeError as e:
  3649. log.debug(
  3650. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3651. )
  3652. while self.collection.get_selected():
  3653. self.delete_first_selected()
  3654. # make sure that the selection shape is deleted, too
  3655. self.delete_selection_shape()
  3656. # if there are no longer objects delete also the exclusion areas shapes
  3657. if not self.collection.get_list():
  3658. self.exc_areas.clear_shapes()
  3659. self.inform.emit('%s...' % _("Object(s) deleted"))
  3660. else:
  3661. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3662. else:
  3663. self.inform.emit(_("Save the work in Editor and try again ..."))
  3664. def delete_first_selected(self):
  3665. # Keep this for later
  3666. try:
  3667. sel_obj = self.collection.get_active()
  3668. name = sel_obj.options["name"]
  3669. isPlotted = sel_obj.options["plot"]
  3670. except AttributeError:
  3671. self.log.debug("Nothing selected for deletion")
  3672. return
  3673. if self.is_legacy is True:
  3674. # Remove plot only if the object was plotted otherwise delaxes will fail
  3675. if isPlotted:
  3676. try:
  3677. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3678. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3679. except Exception as e:
  3680. log.debug("App.delete_first_selected() --> %s" % str(e))
  3681. self.plotcanvas.auto_adjust_axes()
  3682. # Remove from dictionary
  3683. self.collection.delete_active()
  3684. # Clear form
  3685. self.setup_component_editor()
  3686. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3687. def on_set_origin(self):
  3688. """
  3689. Set the origin to the left mouse click position
  3690. :return: None
  3691. """
  3692. # display the message for the user
  3693. # and ask him to click on the desired position
  3694. self.defaults.report_usage("on_set_origin()")
  3695. def origin_replot():
  3696. def worker_task():
  3697. with self.proc_container.new('%s...' % _("Plotting")):
  3698. for obj in self.collection.get_list():
  3699. obj.plot()
  3700. self.plotcanvas.fit_view()
  3701. if self.is_legacy:
  3702. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3703. else:
  3704. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3705. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3706. self.inform.emit(_('Click to set the origin ...'))
  3707. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3708. # first disconnect it as it may have been used by something else
  3709. try:
  3710. self.replot_signal.disconnect()
  3711. except TypeError:
  3712. pass
  3713. self.replot_signal[list].connect(origin_replot)
  3714. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3715. """
  3716. :param event:
  3717. :param location:
  3718. :param noplot:
  3719. :param use_thread:
  3720. :return:
  3721. """
  3722. noplot_sig = noplot
  3723. def worker_task():
  3724. with self.proc_container.new(_("Setting Origin...")):
  3725. obj_list = self.collection.get_list()
  3726. for obj in obj_list:
  3727. obj.offset((x, y))
  3728. self.app_obj.object_changed.emit(obj)
  3729. # Update the object bounding box options
  3730. a, b, c, d = obj.bounds()
  3731. obj.options['xmin'] = a
  3732. obj.options['ymin'] = b
  3733. obj.options['xmax'] = c
  3734. obj.options['ymax'] = d
  3735. self.inform.emit('[success] %s...' % _('Origin set'))
  3736. for obj in obj_list:
  3737. out_name = obj.options["name"]
  3738. if obj.kind == 'gerber':
  3739. obj.source_file = self.export_gerber(
  3740. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3741. elif obj.kind == 'excellon':
  3742. obj.source_file = self.export_excellon(
  3743. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3744. if noplot_sig is False:
  3745. self.replot_signal.emit([])
  3746. if location is not None:
  3747. if len(location) != 2:
  3748. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3749. return 'fail'
  3750. x, y = location
  3751. if use_thread is True:
  3752. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3753. else:
  3754. worker_task()
  3755. self.should_we_save = True
  3756. return
  3757. if event is not None and event.button == 1:
  3758. if self.is_legacy is False:
  3759. event_pos = event.pos
  3760. else:
  3761. event_pos = (event.xdata, event.ydata)
  3762. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3763. if self.grid_status():
  3764. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3765. else:
  3766. pos = pos_canvas
  3767. x = 0 - pos[0]
  3768. y = 0 - pos[1]
  3769. if use_thread is True:
  3770. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3771. else:
  3772. worker_task()
  3773. self.should_we_save = True
  3774. def on_move2origin(self, use_thread=True):
  3775. """
  3776. Move selected objects to origin.
  3777. :param use_thread: Control if to use threaded operation. Boolean.
  3778. :return:
  3779. """
  3780. def worker_task():
  3781. with self.proc_container.new(_("Moving to Origin...")):
  3782. obj_list = self.collection.get_selected()
  3783. if not obj_list:
  3784. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3785. return
  3786. xminlist = []
  3787. yminlist = []
  3788. # first get a bounding box to fit all
  3789. for obj in obj_list:
  3790. xmin, ymin, xmax, ymax = obj.bounds()
  3791. xminlist.append(xmin)
  3792. yminlist.append(ymin)
  3793. # get the minimum x,y for all objects selected
  3794. x = min(xminlist)
  3795. y = min(yminlist)
  3796. for obj in obj_list:
  3797. obj.offset((-x, -y))
  3798. self.app_obj.object_changed.emit(obj)
  3799. # Update the object bounding box options
  3800. a, b, c, d = obj.bounds()
  3801. obj.options['xmin'] = a
  3802. obj.options['ymin'] = b
  3803. obj.options['xmax'] = c
  3804. obj.options['ymax'] = d
  3805. for obj in obj_list:
  3806. obj.plot()
  3807. for obj in obj_list:
  3808. out_name = obj.options["name"]
  3809. if obj.kind == 'gerber':
  3810. obj.source_file = self.export_gerber(
  3811. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3812. elif obj.kind == 'excellon':
  3813. obj.source_file = self.export_excellon(
  3814. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3815. self.inform.emit('[success] %s...' % _('Origin set'))
  3816. if use_thread is True:
  3817. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3818. else:
  3819. worker_task()
  3820. self.should_we_save = True
  3821. def on_jump_to(self, custom_location=None, fit_center=True):
  3822. """
  3823. Jump to a location by setting the mouse cursor location.
  3824. :param custom_location: Jump to a specified point. (x, y) tuple.
  3825. :param fit_center: If to fit view. Boolean.
  3826. :return:
  3827. """
  3828. self.defaults.report_usage("on_jump_to()")
  3829. if not custom_location:
  3830. dia_box_location = None
  3831. try:
  3832. dia_box_location = eval(self.clipboard.text())
  3833. except Exception:
  3834. pass
  3835. if type(dia_box_location) == tuple:
  3836. dia_box_location = str(dia_box_location)
  3837. else:
  3838. dia_box_location = None
  3839. # dia_box = Dialog_box(title=_("Jump to ..."),
  3840. # label=_("Enter the coordinates in format X,Y:"),
  3841. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3842. # initial_text=dia_box_location)
  3843. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3844. label=_("Enter the coordinates in format X,Y:"),
  3845. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3846. initial_text=dia_box_location,
  3847. reference=self.defaults['global_jump_ref'])
  3848. if dia_box.ok is True:
  3849. try:
  3850. location = eval(dia_box.location)
  3851. if not isinstance(location, tuple):
  3852. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3853. return
  3854. if dia_box.reference == 'rel':
  3855. rel_x = self.mouse[0] + location[0]
  3856. rel_y = self.mouse[1] + location[1]
  3857. location = (rel_x, rel_y)
  3858. self.defaults['global_jump_ref'] = dia_box.reference
  3859. except Exception:
  3860. return
  3861. else:
  3862. return
  3863. else:
  3864. location = custom_location
  3865. self.jump_signal.emit(location)
  3866. if fit_center:
  3867. self.plotcanvas.fit_center(loc=location)
  3868. cursor = QtGui.QCursor()
  3869. if self.is_legacy is False:
  3870. # I don't know where those differences come from but they are constant for the current
  3871. # execution of the application and they are multiples of a value around 0.0263mm.
  3872. # In a random way sometimes they are more sometimes they are less
  3873. # if units == 'MM':
  3874. # cal_factor = 0.0263
  3875. # else:
  3876. # cal_factor = 0.0263 / 25.4
  3877. cal_location = (location[0], location[1])
  3878. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3879. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3880. j_pos = (
  3881. int(canvas_origin.x() + round(jump_loc[0])),
  3882. int(canvas_origin.y() + round(jump_loc[1]))
  3883. )
  3884. cursor.setPos(j_pos[0], j_pos[1])
  3885. else:
  3886. # find the canvas origin which is in the top left corner
  3887. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3888. # determine the coordinates for the lowest left point of the canvas
  3889. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3890. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3891. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3892. # canvas) and the point (width, height) is in the top-right location
  3893. loc = self.plotcanvas.axes.transData.transform_point(location)
  3894. j_pos = (
  3895. int(x0 + loc[0]),
  3896. int(y0 - loc[1])
  3897. )
  3898. cursor.setPos(j_pos[0], j_pos[1])
  3899. self.plotcanvas.mouse = [location[0], location[1]]
  3900. if self.defaults["global_cursor_color_enabled"] is True:
  3901. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3902. else:
  3903. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3904. if self.grid_status():
  3905. # Update cursor
  3906. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3907. symbol='++', edge_color=self.cursor_color_3D,
  3908. edge_width=self.defaults["global_cursor_width"],
  3909. size=self.defaults["global_cursor_size"])
  3910. # Set the relative position label
  3911. dx = location[0] - float(self.rel_point1[0])
  3912. dy = location[1] - float(self.rel_point1[1])
  3913. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3914. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3915. # # Set the position label
  3916. #
  3917. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3918. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3919. units = self.defaults["units"].lower()
  3920. self.plotcanvas.text_hud.text = \
  3921. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3922. dx, units, dy, units, location[0], units, location[1], units)
  3923. self.inform.emit('[success] %s' % _("Done."))
  3924. return location
  3925. def on_locate(self, obj, fit_center=True):
  3926. """
  3927. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3928. :param obj: The object on which to locate certain points
  3929. :param fit_center: If to fit view. Boolean.
  3930. :return: A point location. (x, y) tuple.
  3931. """
  3932. self.defaults.report_usage("on_locate()")
  3933. if obj is None:
  3934. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3935. return 'fail'
  3936. class DialogBoxChoice(QtWidgets.QDialog):
  3937. def __init__(self, title=None, icon=None, choice='bl'):
  3938. """
  3939. :param title: string with the window title
  3940. """
  3941. super(DialogBoxChoice, self).__init__()
  3942. self.ok = False
  3943. self.setWindowIcon(icon)
  3944. self.setWindowTitle(str(title))
  3945. self.form = QtWidgets.QFormLayout(self)
  3946. self.ref_radio = RadioSet([
  3947. {"label": _("Bottom-Left"), "value": "bl"},
  3948. {"label": _("Top-Left"), "value": "tl"},
  3949. {"label": _("Bottom-Right"), "value": "br"},
  3950. {"label": _("Top-Right"), "value": "tr"},
  3951. {"label": _("Center"), "value": "c"}
  3952. ], orientation='vertical', stretch=False)
  3953. self.ref_radio.set_value(choice)
  3954. self.form.addRow(self.ref_radio)
  3955. self.button_box = QtWidgets.QDialogButtonBox(
  3956. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3957. Qt.Horizontal, parent=self)
  3958. self.form.addRow(self.button_box)
  3959. self.button_box.accepted.connect(self.accept)
  3960. self.button_box.rejected.connect(self.reject)
  3961. if self.exec_() == QtWidgets.QDialog.Accepted:
  3962. self.ok = True
  3963. self.location_point = self.ref_radio.get_value()
  3964. else:
  3965. self.ok = False
  3966. self.location_point = None
  3967. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3968. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3969. choice=self.defaults['global_locate_pt'])
  3970. if dia_box.ok is True:
  3971. try:
  3972. location_point = dia_box.location_point
  3973. self.defaults['global_locate_pt'] = dia_box.location_point
  3974. except Exception:
  3975. return
  3976. else:
  3977. return
  3978. loc_b = obj.bounds()
  3979. if location_point == 'bl':
  3980. location = (loc_b[0], loc_b[1])
  3981. elif location_point == 'tl':
  3982. location = (loc_b[0], loc_b[3])
  3983. elif location_point == 'br':
  3984. location = (loc_b[2], loc_b[1])
  3985. elif location_point == 'tr':
  3986. location = (loc_b[2], loc_b[3])
  3987. else:
  3988. # center
  3989. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3990. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3991. location = (cx, cy)
  3992. self.locate_signal.emit(location, location_point)
  3993. if fit_center:
  3994. self.plotcanvas.fit_center(loc=location)
  3995. cursor = QtGui.QCursor()
  3996. if self.is_legacy is False:
  3997. # I don't know where those differences come from but they are constant for the current
  3998. # execution of the application and they are multiples of a value around 0.0263mm.
  3999. # In a random way sometimes they are more sometimes they are less
  4000. # if units == 'MM':
  4001. # cal_factor = 0.0263
  4002. # else:
  4003. # cal_factor = 0.0263 / 25.4
  4004. cal_location = (location[0], location[1])
  4005. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4006. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4007. j_pos = (
  4008. int(canvas_origin.x() + round(jump_loc[0])),
  4009. int(canvas_origin.y() + round(jump_loc[1]))
  4010. )
  4011. cursor.setPos(j_pos[0], j_pos[1])
  4012. else:
  4013. # find the canvas origin which is in the top left corner
  4014. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4015. # determine the coordinates for the lowest left point of the canvas
  4016. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4017. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4018. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4019. # canvas) and the point (width, height) is in the top-right location
  4020. loc = self.plotcanvas.axes.transData.transform_point(location)
  4021. j_pos = (
  4022. int(x0 + loc[0]),
  4023. int(y0 - loc[1])
  4024. )
  4025. cursor.setPos(j_pos[0], j_pos[1])
  4026. self.plotcanvas.mouse = [location[0], location[1]]
  4027. if self.defaults["global_cursor_color_enabled"] is True:
  4028. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4029. else:
  4030. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4031. if self.grid_status():
  4032. # Update cursor
  4033. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4034. symbol='++', edge_color=self.cursor_color_3D,
  4035. edge_width=self.defaults["global_cursor_width"],
  4036. size=self.defaults["global_cursor_size"])
  4037. # Set the relative position label
  4038. self.dx = location[0] - float(self.rel_point1[0])
  4039. self.dy = location[1] - float(self.rel_point1[1])
  4040. # Set the position label
  4041. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4042. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4043. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4044. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4045. units = self.defaults["units"].lower()
  4046. self.plotcanvas.text_hud.text = \
  4047. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4048. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4049. self.inform.emit('[success] %s' % _("Done."))
  4050. return location
  4051. def on_copy_command(self):
  4052. """
  4053. Will copy a selection of objects, creating new objects.
  4054. :return:
  4055. """
  4056. self.defaults.report_usage("on_copy_command()")
  4057. def initialize(obj_init, app):
  4058. """
  4059. :param obj_init: the new object
  4060. :type obj_init: class
  4061. :param app: An instance of the App class
  4062. :type app: App
  4063. :return: None
  4064. :rtype:
  4065. """
  4066. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4067. try:
  4068. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4069. except AttributeError:
  4070. pass
  4071. try:
  4072. obj_init.apertures = deepcopy(obj.apertures)
  4073. except AttributeError:
  4074. pass
  4075. try:
  4076. if obj.tools:
  4077. obj_init.tools = deepcopy(obj.tools)
  4078. except Exception as err:
  4079. log.debug("App.on_copy_command() --> %s" % str(err))
  4080. try:
  4081. obj_init.source_file = deepcopy(obj.source_file)
  4082. except (AttributeError, TypeError):
  4083. pass
  4084. def initialize_excellon(obj_init, app):
  4085. obj_init.source_file = deepcopy(obj.source_file)
  4086. obj_init.tools = deepcopy(obj.tools)
  4087. # drills are offset, so they need to be deep copied
  4088. obj_init.drills = deepcopy(obj.drills)
  4089. # slots are offset, so they need to be deep copied
  4090. obj_init.slots = deepcopy(obj.slots)
  4091. obj_init.create_geometry()
  4092. def initialize_script(obj_init, app_obj):
  4093. obj_init.source_file = deepcopy(obj.source_file)
  4094. def initialize_document(obj_init, app_obj):
  4095. obj_init.source_file = deepcopy(obj.source_file)
  4096. for obj in self.collection.get_selected():
  4097. obj_name = obj.options["name"]
  4098. try:
  4099. if isinstance(obj, ExcellonObject):
  4100. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4101. elif isinstance(obj, GerberObject):
  4102. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4103. elif isinstance(obj, GeometryObject):
  4104. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4105. elif isinstance(obj, ScriptObject):
  4106. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4107. elif isinstance(obj, DocumentObject):
  4108. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4109. except Exception as e:
  4110. return "Operation failed: %s" % str(e)
  4111. def on_copy_object2(self, custom_name):
  4112. def initialize_geometry(obj_init, app):
  4113. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4114. try:
  4115. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4116. except AttributeError:
  4117. pass
  4118. try:
  4119. obj_init.apertures = deepcopy(obj.apertures)
  4120. except AttributeError:
  4121. pass
  4122. try:
  4123. if obj.tools:
  4124. obj_init.tools = deepcopy(obj.tools)
  4125. except Exception as ee:
  4126. log.debug("on_copy_object2() --> %s" % str(ee))
  4127. def initialize_gerber(obj_init, app):
  4128. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4129. obj_init.apertures = deepcopy(obj.apertures)
  4130. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4131. def initialize_excellon(obj_init, app):
  4132. obj_init.tools = deepcopy(obj.tools)
  4133. # drills are offset, so they need to be deep copied
  4134. obj_init.drills = deepcopy(obj.drills)
  4135. # slots are offset, so they need to be deep copied
  4136. obj_init.slots = deepcopy(obj.slots)
  4137. obj_init.create_geometry()
  4138. for obj in self.collection.get_selected():
  4139. obj_name = obj.options["name"]
  4140. try:
  4141. if isinstance(obj, ExcellonObject):
  4142. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4143. elif isinstance(obj, GerberObject):
  4144. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4145. elif isinstance(obj, GeometryObject):
  4146. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4147. except Exception as er:
  4148. return "Operation failed: %s" % str(er)
  4149. def on_rename_object(self, text):
  4150. """
  4151. Will rename an object.
  4152. :param text: New name for the object.
  4153. :return:
  4154. """
  4155. self.defaults.report_usage("on_rename_object()")
  4156. named_obj = self.collection.get_active()
  4157. for obj in named_obj:
  4158. if obj is list:
  4159. self.on_rename_object(text)
  4160. else:
  4161. try:
  4162. obj.options['name'] = text
  4163. except Exception as e:
  4164. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4165. def convert_any2geo(self):
  4166. """
  4167. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4168. :return:
  4169. """
  4170. self.defaults.report_usage("convert_any2geo()")
  4171. def initialize(obj_init, app):
  4172. obj_init.solid_geometry = obj.solid_geometry
  4173. try:
  4174. obj_init.follow_geometry = obj.follow_geometry
  4175. except AttributeError:
  4176. pass
  4177. try:
  4178. obj_init.apertures = obj.apertures
  4179. except AttributeError:
  4180. pass
  4181. try:
  4182. if obj.tools:
  4183. obj_init.tools = obj.tools
  4184. except AttributeError:
  4185. pass
  4186. def initialize_excellon(obj_init, app):
  4187. # objs = self.collection.get_selected()
  4188. # GeometryObject.merge(objs, obj)
  4189. solid_geo = []
  4190. for tool in obj.tools:
  4191. for geo in obj.tools[tool]['solid_geometry']:
  4192. solid_geo.append(geo)
  4193. obj_init.solid_geometry = deepcopy(solid_geo)
  4194. if not self.collection.get_selected():
  4195. log.warning("App.convert_any2geo --> No object selected")
  4196. self.inform.emit('[WARNING_NOTCL] %s' %
  4197. _("No object is selected. Select an object and try again."))
  4198. return
  4199. for obj in self.collection.get_selected():
  4200. obj_name = obj.options["name"]
  4201. try:
  4202. if isinstance(obj, ExcellonObject):
  4203. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4204. else:
  4205. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4206. except Exception as e:
  4207. return "Operation failed: %s" % str(e)
  4208. def convert_any2gerber(self):
  4209. """
  4210. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4211. :return:
  4212. """
  4213. self.defaults.report_usage("convert_any2gerber()")
  4214. def initialize_geometry(obj_init, app):
  4215. apertures = {}
  4216. apid = 0
  4217. apertures[str(apid)] = {}
  4218. apertures[str(apid)]['geometry'] = []
  4219. for obj_orig in obj.solid_geometry:
  4220. new_elem = {}
  4221. new_elem['solid'] = obj_orig
  4222. try:
  4223. new_elem['follow'] = obj_orig.exterior
  4224. except AttributeError:
  4225. pass
  4226. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4227. apertures[str(apid)]['size'] = 0.0
  4228. apertures[str(apid)]['type'] = 'C'
  4229. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4230. obj_init.apertures = deepcopy(apertures)
  4231. def initialize_excellon(obj_init, app):
  4232. apertures = {}
  4233. apid = 10
  4234. for tool in obj.tools:
  4235. apertures[str(apid)] = {}
  4236. apertures[str(apid)]['geometry'] = []
  4237. for geo in obj.tools[tool]['solid_geometry']:
  4238. new_el = {}
  4239. new_el['solid'] = geo
  4240. new_el['follow'] = geo.exterior
  4241. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4242. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4243. apertures[str(apid)]['type'] = 'C'
  4244. apid += 1
  4245. # create solid_geometry
  4246. solid_geometry = []
  4247. for apid in apertures:
  4248. for geo_el in apertures[apid]['geometry']:
  4249. solid_geometry.append(geo_el['solid'])
  4250. solid_geometry = MultiPolygon(solid_geometry)
  4251. solid_geometry = solid_geometry.buffer(0.0000001)
  4252. obj_init.solid_geometry = deepcopy(solid_geometry)
  4253. obj_init.apertures = deepcopy(apertures)
  4254. # clear the working objects (perhaps not necessary due of Python GC)
  4255. apertures.clear()
  4256. if not self.collection.get_selected():
  4257. log.warning("App.convert_any2gerber --> No object selected")
  4258. self.inform.emit('[WARNING_NOTCL] %s' %
  4259. _("No object is selected. Select an object and try again."))
  4260. return
  4261. for obj in self.collection.get_selected():
  4262. obj_name = obj.options["name"]
  4263. try:
  4264. if isinstance(obj, ExcellonObject):
  4265. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4266. elif isinstance(obj, GeometryObject):
  4267. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4268. else:
  4269. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4270. except Exception as e:
  4271. return "Operation failed: %s" % str(e)
  4272. def abort_all_tasks(self):
  4273. """
  4274. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4275. on the first possible occasion.
  4276. :return:
  4277. """
  4278. if self.abort_flag is False:
  4279. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4280. self.abort_flag = True
  4281. self.cleanup.emit()
  4282. def app_is_idle(self):
  4283. if self.abort_flag:
  4284. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4285. self.abort_flag = False
  4286. def on_selectall(self):
  4287. """
  4288. Will draw a selection box shape around the selected objects.
  4289. :return:
  4290. """
  4291. self.defaults.report_usage("on_selectall()")
  4292. # delete the possible selection box around a possible selected object
  4293. self.delete_selection_shape()
  4294. for name in self.collection.get_names():
  4295. self.collection.set_active(name)
  4296. curr_sel_obj = self.collection.get_by_name(name)
  4297. # create the selection box around the selected object
  4298. if self.defaults['global_selection_shape'] is True:
  4299. self.draw_selection_shape(curr_sel_obj)
  4300. def on_toggle_preferences(self):
  4301. pref_open = False
  4302. for idx in range(self.ui.plot_tab_area.count()):
  4303. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4304. pref_open = True
  4305. if pref_open:
  4306. for idx in range(self.ui.plot_tab_area.count()):
  4307. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4308. self.ui.plot_tab_area.removeTab(idx)
  4309. break
  4310. self.ui.pref_status_label.setStyleSheet("")
  4311. else:
  4312. self.on_preferences()
  4313. def on_preferences(self):
  4314. """
  4315. Adds the Preferences in a Tab in Plot Area
  4316. :return:
  4317. """
  4318. # add the tab if it was closed
  4319. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4320. # delete the absolute and relative position and messages in the infobar
  4321. self.ui.position_label.setText("")
  4322. # self.ui.rel_position_label.setText("")
  4323. # Switch plot_area to preferences page
  4324. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4325. # self.ui.show()
  4326. self.ui.pref_status_label.setStyleSheet("""
  4327. QLabel
  4328. {
  4329. color: black;
  4330. background-color: lightseagreen;
  4331. }
  4332. """
  4333. )
  4334. # detect changes in the preferences
  4335. for idx in range(self.ui.pref_tab_area.count()):
  4336. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4337. try:
  4338. try:
  4339. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4340. except (TypeError, AttributeError):
  4341. pass
  4342. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4343. except AttributeError:
  4344. pass
  4345. try:
  4346. try:
  4347. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4348. except (TypeError, AttributeError):
  4349. pass
  4350. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4351. except AttributeError:
  4352. pass
  4353. try:
  4354. try:
  4355. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4356. except (TypeError, AttributeError):
  4357. pass
  4358. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4359. except AttributeError:
  4360. pass
  4361. try:
  4362. try:
  4363. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4364. except (TypeError, AttributeError):
  4365. pass
  4366. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4367. except AttributeError:
  4368. pass
  4369. try:
  4370. try:
  4371. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4372. except (TypeError, AttributeError):
  4373. pass
  4374. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4375. except AttributeError:
  4376. pass
  4377. def on_tools_database(self, source='app'):
  4378. """
  4379. Adds the Tools Database in a Tab in Plot Area.
  4380. :return:
  4381. """
  4382. for idx in range(self.ui.plot_tab_area.count()):
  4383. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4384. # there can be only one instance of Tools Database at one time
  4385. return
  4386. if source == 'app':
  4387. self.tools_db_tab = ToolsDB2(
  4388. app=self,
  4389. parent=self.ui,
  4390. callback_on_edited=self.on_tools_db_edited,
  4391. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4392. )
  4393. elif source == 'ncc':
  4394. self.tools_db_tab = ToolsDB2(
  4395. app=self,
  4396. parent=self.ui,
  4397. callback_on_edited=self.on_tools_db_edited,
  4398. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4399. )
  4400. elif source == 'paint':
  4401. self.tools_db_tab = ToolsDB2(
  4402. app=self,
  4403. parent=self.ui,
  4404. callback_on_edited=self.on_tools_db_edited,
  4405. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4406. )
  4407. elif source == 'iso':
  4408. self.tools_db_tab = ToolsDB2(
  4409. app=self,
  4410. parent=self.ui,
  4411. callback_on_edited=self.on_tools_db_edited,
  4412. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4413. )
  4414. # add the tab if it was closed
  4415. try:
  4416. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4417. self.tools_db_tab.setObjectName("database_tab")
  4418. except Exception as e:
  4419. log.debug("App.on_tools_database() --> %s" % str(e))
  4420. return
  4421. # delete the absolute and relative position and messages in the infobar
  4422. self.ui.position_label.setText("")
  4423. # self.ui.rel_position_label.setText("")
  4424. # Switch plot_area to preferences page
  4425. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4426. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4427. self.tools_db_tab.ui_connect()
  4428. def on_tools_db_edited(self):
  4429. """
  4430. Executed whenever a tool is edited in Tools Database.
  4431. Will color the text of the Tools Database tab to Red color.
  4432. :return:
  4433. """
  4434. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4435. for idx in range(self.ui.plot_tab_area.count()):
  4436. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4437. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4438. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4439. self.tools_db_changed_flag = True
  4440. def on_geometry_tool_add_from_db_executed(self, tool):
  4441. """
  4442. Here add the tool from DB in the selected geometry object.
  4443. :return:
  4444. """
  4445. tool_from_db = deepcopy(tool)
  4446. obj = self.collection.get_active()
  4447. if obj.kind == 'geometry':
  4448. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4449. # close the tab and delete it
  4450. for idx in range(self.ui.plot_tab_area.count()):
  4451. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4452. wdg = self.ui.plot_tab_area.widget(idx)
  4453. wdg.deleteLater()
  4454. self.ui.plot_tab_area.removeTab(idx)
  4455. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4456. elif obj.kind == 'gerber':
  4457. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4458. # close the tab and delete it
  4459. for idx in range(self.ui.plot_tab_area.count()):
  4460. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4461. wdg = self.ui.plot_tab_area.widget(idx)
  4462. wdg.deleteLater()
  4463. self.ui.plot_tab_area.removeTab(idx)
  4464. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4465. else:
  4466. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4467. def on_plot_area_tab_closed(self, tab_obj_name):
  4468. """
  4469. Executed whenever a QTab is closed in the Plot Area.
  4470. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4471. :return:
  4472. """
  4473. if tab_obj_name == "preferences_tab":
  4474. self.preferencesUiManager.on_close_preferences_tab()
  4475. elif tab_obj_name == "database_tab":
  4476. # disconnect the signals from the table widget in tab
  4477. self.tools_db_tab.ui_disconnect()
  4478. if self.tools_db_changed_flag is True:
  4479. msgbox = QtWidgets.QMessageBox()
  4480. msgbox.setText(_("One or more Tools are edited.\n"
  4481. "Do you want to update the Tools Database?"))
  4482. msgbox.setWindowTitle(_("Save Tools Database"))
  4483. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4484. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4485. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4486. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4487. msgbox.setDefaultButton(bt_yes)
  4488. msgbox.exec_()
  4489. response = msgbox.clickedButton()
  4490. if response == bt_yes:
  4491. self.tools_db_tab.on_save_tools_db()
  4492. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4493. else:
  4494. self.tools_db_changed_flag = False
  4495. self.inform.emit('')
  4496. return
  4497. self.tools_db_tab.deleteLater()
  4498. elif tab_obj_name == "text_editor_tab":
  4499. self.toggle_codeeditor = False
  4500. elif tab_obj_name == "bookmarks_tab":
  4501. self.book_dialog_tab.rebuild_actions()
  4502. self.book_dialog_tab.deleteLater()
  4503. else:
  4504. return
  4505. # def on_plotarea_tab_closed(self, tab_idx):
  4506. # """
  4507. #
  4508. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4509. # :return:
  4510. # """
  4511. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4512. #
  4513. # if widget is not None:
  4514. # widget.deleteLater()
  4515. # self.ui.plot_tab_area.removeTab(tab_idx)
  4516. def on_flipy(self):
  4517. """
  4518. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4519. :return:
  4520. """
  4521. self.defaults.report_usage("on_flipy()")
  4522. obj_list = self.collection.get_selected()
  4523. xminlist = []
  4524. yminlist = []
  4525. xmaxlist = []
  4526. ymaxlist = []
  4527. if not obj_list:
  4528. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4529. else:
  4530. try:
  4531. # first get a bounding box to fit all
  4532. for obj in obj_list:
  4533. xmin, ymin, xmax, ymax = obj.bounds()
  4534. xminlist.append(xmin)
  4535. yminlist.append(ymin)
  4536. xmaxlist.append(xmax)
  4537. ymaxlist.append(ymax)
  4538. # get the minimum x,y and maximum x,y for all objects selected
  4539. xminimal = min(xminlist)
  4540. yminimal = min(yminlist)
  4541. xmaximal = max(xmaxlist)
  4542. ymaximal = max(ymaxlist)
  4543. px = 0.5 * (xminimal + xmaximal)
  4544. py = 0.5 * (yminimal + ymaximal)
  4545. # execute mirroring
  4546. for obj in obj_list:
  4547. obj.mirror('X', [px, py])
  4548. obj.plot()
  4549. self.app_obj.object_changed.emit(obj)
  4550. self.inform.emit('[success] %s' %
  4551. _("Flip on Y axis done."))
  4552. except Exception as e:
  4553. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4554. return
  4555. def on_flipx(self):
  4556. """
  4557. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4558. :return:
  4559. """
  4560. self.defaults.report_usage("on_flipx()")
  4561. obj_list = self.collection.get_selected()
  4562. xminlist = []
  4563. yminlist = []
  4564. xmaxlist = []
  4565. ymaxlist = []
  4566. if not obj_list:
  4567. self.inform.emit('[WARNING_NOTCL] %s' %
  4568. _("No object selected to Flip on X axis."))
  4569. else:
  4570. try:
  4571. # first get a bounding box to fit all
  4572. for obj in obj_list:
  4573. xmin, ymin, xmax, ymax = obj.bounds()
  4574. xminlist.append(xmin)
  4575. yminlist.append(ymin)
  4576. xmaxlist.append(xmax)
  4577. ymaxlist.append(ymax)
  4578. # get the minimum x,y and maximum x,y for all objects selected
  4579. xminimal = min(xminlist)
  4580. yminimal = min(yminlist)
  4581. xmaximal = max(xmaxlist)
  4582. ymaximal = max(ymaxlist)
  4583. px = 0.5 * (xminimal + xmaximal)
  4584. py = 0.5 * (yminimal + ymaximal)
  4585. # execute mirroring
  4586. for obj in obj_list:
  4587. obj.mirror('Y', [px, py])
  4588. obj.plot()
  4589. self.app_obj.object_changed.emit(obj)
  4590. self.inform.emit('[success] %s' %
  4591. _("Flip on X axis done."))
  4592. except Exception as e:
  4593. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4594. return
  4595. def on_rotate(self, silent=False, preset=None):
  4596. """
  4597. Executed when Options -> Rotate Selection menu entry is clicked.
  4598. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4599. :param preset: A value to be used as predefined angle for rotation.
  4600. :return:
  4601. """
  4602. self.defaults.report_usage("on_rotate()")
  4603. obj_list = self.collection.get_selected()
  4604. xminlist = []
  4605. yminlist = []
  4606. xmaxlist = []
  4607. ymaxlist = []
  4608. if not obj_list:
  4609. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4610. else:
  4611. if silent is False:
  4612. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4613. min=-360, max=360, decimals=4,
  4614. init_val=float(self.defaults['tools_transform_rotate']))
  4615. num, ok = rotatebox.get_value()
  4616. else:
  4617. num = preset
  4618. ok = True
  4619. if ok:
  4620. try:
  4621. # first get a bounding box to fit all
  4622. for obj in obj_list:
  4623. xmin, ymin, xmax, ymax = obj.bounds()
  4624. xminlist.append(xmin)
  4625. yminlist.append(ymin)
  4626. xmaxlist.append(xmax)
  4627. ymaxlist.append(ymax)
  4628. # get the minimum x,y and maximum x,y for all objects selected
  4629. xminimal = min(xminlist)
  4630. yminimal = min(yminlist)
  4631. xmaximal = max(xmaxlist)
  4632. ymaximal = max(ymaxlist)
  4633. px = 0.5 * (xminimal + xmaximal)
  4634. py = 0.5 * (yminimal + ymaximal)
  4635. for sel_obj in obj_list:
  4636. sel_obj.rotate(-float(num), point=(px, py))
  4637. sel_obj.plot()
  4638. self.app_obj.object_changed.emit(sel_obj)
  4639. self.inform.emit('[success] %s' % _("Rotation done."))
  4640. except Exception as e:
  4641. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4642. return
  4643. def on_skewx(self):
  4644. """
  4645. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4646. :return:
  4647. """
  4648. self.defaults.report_usage("on_skewx()")
  4649. obj_list = self.collection.get_selected()
  4650. xminlist = []
  4651. yminlist = []
  4652. if not obj_list:
  4653. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4654. else:
  4655. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4656. min=-360, max=360, decimals=4,
  4657. init_val=float(self.defaults['tools_transform_skew_x']))
  4658. num, ok = skewxbox.get_value()
  4659. if ok:
  4660. # first get a bounding box to fit all
  4661. for obj in obj_list:
  4662. xmin, ymin, xmax, ymax = obj.bounds()
  4663. xminlist.append(xmin)
  4664. yminlist.append(ymin)
  4665. # get the minimum x,y and maximum x,y for all objects selected
  4666. xminimal = min(xminlist)
  4667. yminimal = min(yminlist)
  4668. for obj in obj_list:
  4669. obj.skew(num, 0, point=(xminimal, yminimal))
  4670. obj.plot()
  4671. self.app_obj.object_changed.emit(obj)
  4672. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4673. def on_skewy(self):
  4674. """
  4675. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4676. :return:
  4677. """
  4678. self.defaults.report_usage("on_skewy()")
  4679. obj_list = self.collection.get_selected()
  4680. xminlist = []
  4681. yminlist = []
  4682. if not obj_list:
  4683. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4684. else:
  4685. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4686. min=-360, max=360, decimals=4,
  4687. init_val=float(self.defaults['tools_transform_skew_y']))
  4688. num, ok = skewybox.get_value()
  4689. if ok:
  4690. # first get a bounding box to fit all
  4691. for obj in obj_list:
  4692. xmin, ymin, xmax, ymax = obj.bounds()
  4693. xminlist.append(xmin)
  4694. yminlist.append(ymin)
  4695. # get the minimum x,y and maximum x,y for all objects selected
  4696. xminimal = min(xminlist)
  4697. yminimal = min(yminlist)
  4698. for obj in obj_list:
  4699. obj.skew(0, num, point=(xminimal, yminimal))
  4700. obj.plot()
  4701. self.app_obj.object_changed.emit(obj)
  4702. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4703. def on_plots_updated(self):
  4704. """
  4705. Callback used to report when the plots have changed.
  4706. Adjust axes and zooms to fit.
  4707. :return: None
  4708. """
  4709. if self.is_legacy is False:
  4710. self.plotcanvas.update()
  4711. else:
  4712. self.plotcanvas.auto_adjust_axes()
  4713. self.on_zoom_fit()
  4714. self.collection.update_view()
  4715. # self.inform.emit(_("Plots updated ..."))
  4716. def on_toolbar_replot(self):
  4717. """
  4718. Callback for toolbar button. Re-plots all objects.
  4719. :return: None
  4720. """
  4721. self.log.debug("on_toolbar_replot()")
  4722. try:
  4723. self.collection.get_active().read_form()
  4724. except AttributeError:
  4725. self.log.debug("on_toolbar_replot(): AttributeError")
  4726. pass
  4727. self.plot_all()
  4728. def grid_status(self):
  4729. return True if self.ui.grid_snap_btn.isChecked() else False
  4730. def populate_cmenu_grids(self):
  4731. units = self.defaults['units'].lower()
  4732. # for act in self.ui.cmenu_gridmenu.actions():
  4733. # act.triggered.disconnect()
  4734. self.ui.cmenu_gridmenu.clear()
  4735. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4736. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4737. _("Grid On/Off"))
  4738. grid_toggle.setCheckable(True)
  4739. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4740. self.ui.cmenu_gridmenu.addSeparator()
  4741. for grid in sorted_list:
  4742. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4743. "%s" % str(grid))
  4744. action.triggered.connect(self.set_grid)
  4745. self.ui.cmenu_gridmenu.addSeparator()
  4746. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4747. _("Add"))
  4748. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4749. _("Delete"))
  4750. grid_add.triggered.connect(self.on_grid_add)
  4751. grid_delete.triggered.connect(self.on_grid_delete)
  4752. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4753. def set_grid(self):
  4754. menu_action = self.sender()
  4755. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4756. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4757. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4758. def on_grid_add(self):
  4759. # ## Current application units in lower Case
  4760. units = self.defaults['units'].lower()
  4761. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4762. text=_('Enter a Grid Value:'),
  4763. min=0.0000, max=99.9999, decimals=4)
  4764. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4765. val, ok = grid_add_popup.get_value()
  4766. if ok:
  4767. if float(val) == 0:
  4768. self.inform.emit('[WARNING_NOTCL] %s' %
  4769. _("Please enter a grid value with non-zero value, in Float format."))
  4770. return
  4771. else:
  4772. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4773. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4774. self.inform.emit('[success] %s...' % _("New Grid added"))
  4775. else:
  4776. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4777. else:
  4778. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4779. def on_grid_delete(self):
  4780. # ## Current application units in lower Case
  4781. units = self.defaults['units'].lower()
  4782. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4783. text='Enter a Grid Value:',
  4784. min=0.0000, max=99.9999, decimals=4)
  4785. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4786. val, ok = grid_del_popup.get_value()
  4787. if ok:
  4788. if float(val) == 0:
  4789. self.inform.emit('[WARNING_NOTCL] %s' %
  4790. _("Please enter a grid value with non-zero value, in Float format."))
  4791. return
  4792. else:
  4793. try:
  4794. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4795. except ValueError:
  4796. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4797. return
  4798. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4799. else:
  4800. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4801. def on_shortcut_list(self):
  4802. self.defaults.report_usage("on_shortcut_list()")
  4803. # add the tab if it was closed
  4804. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4805. # delete the absolute and relative position and messages in the infobar
  4806. self.ui.position_label.setText("")
  4807. # self.ui.rel_position_label.setText("")
  4808. # Switch plot_area to preferences page
  4809. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4810. # self.ui.show()
  4811. def on_select_tab(self, name):
  4812. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4813. if self.ui.splitter.sizes()[0] == 0:
  4814. self.ui.splitter.setSizes([1, 1])
  4815. else:
  4816. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4817. self.ui.splitter.setSizes([0, 1])
  4818. if name == 'project':
  4819. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4820. elif name == 'selected':
  4821. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4822. elif name == 'tool':
  4823. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4824. def on_copy_name(self):
  4825. self.defaults.report_usage("on_copy_name()")
  4826. obj = self.collection.get_active()
  4827. try:
  4828. name = obj.options["name"]
  4829. except AttributeError:
  4830. log.debug("on_copy_name() --> No object selected to copy it's name")
  4831. self.inform.emit('[WARNING_NOTCL] %s' %
  4832. _(" No object selected to copy it's name"))
  4833. return
  4834. self.clipboard.setText(name)
  4835. self.inform.emit(_("Name copied on clipboard ..."))
  4836. def on_mouse_click_over_plot(self, event):
  4837. """
  4838. Default actions are:
  4839. :param event: Contains information about the event, like which button
  4840. was clicked, the pixel coordinates and the axes coordinates.
  4841. :return: None
  4842. """
  4843. self.pos = []
  4844. if self.is_legacy is False:
  4845. event_pos = event.pos
  4846. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4847. # # Set the mouse button for panning
  4848. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4849. else:
  4850. event_pos = (event.xdata, event.ydata)
  4851. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4852. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4853. # So it can receive key presses
  4854. self.plotcanvas.native.setFocus()
  4855. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4856. if self.grid_status():
  4857. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4858. else:
  4859. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4860. try:
  4861. if event.button == 1:
  4862. # Reset here the relative coordinates so there is a new reference on the click position
  4863. if self.rel_point1 is None:
  4864. self.rel_point1 = self.pos
  4865. else:
  4866. self.rel_point2 = copy(self.rel_point1)
  4867. self.rel_point1 = self.pos
  4868. self.on_mouse_move_over_plot(event, origin_click=True)
  4869. except Exception as e:
  4870. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4871. def on_mouse_double_click_over_plot(self, event):
  4872. if event.button == 1:
  4873. self.doubleclick = True
  4874. def on_mouse_move_over_plot(self, event, origin_click=None):
  4875. """
  4876. Callback for the mouse motion event over the plot.
  4877. :param event: Contains information about the event.
  4878. :param origin_click
  4879. :return: None
  4880. """
  4881. if self.is_legacy is False:
  4882. event_pos = event.pos
  4883. if self.defaults["global_pan_button"] == '2':
  4884. pan_button = 2
  4885. else:
  4886. pan_button = 3
  4887. self.event_is_dragging = event.is_dragging
  4888. else:
  4889. event_pos = (event.xdata, event.ydata)
  4890. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4891. if self.defaults["global_pan_button"] == '2':
  4892. pan_button = 3
  4893. else:
  4894. pan_button = 2
  4895. self.event_is_dragging = self.plotcanvas.is_dragging
  4896. # So it can receive key presses but not when the Tcl Shell is active
  4897. if not self.ui.shell_dock.isVisible():
  4898. if not self.plotcanvas.native.hasFocus():
  4899. self.plotcanvas.native.setFocus()
  4900. self.pos_jump = event_pos
  4901. self.ui.popMenu.mouse_is_panning = False
  4902. if origin_click is None:
  4903. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4904. if event.button == pan_button and self.event_is_dragging == 1:
  4905. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4906. if self.ui.popMenu.popup_active:
  4907. self.ui.popMenu.popup_active = False
  4908. return
  4909. self.ui.popMenu.mouse_is_panning = True
  4910. return
  4911. if self.rel_point1 is not None:
  4912. try: # May fail in case mouse not within axes
  4913. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4914. if pos_canvas[0] is None or pos_canvas[1] is None:
  4915. return
  4916. if self.grid_status():
  4917. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4918. # Update cursor
  4919. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4920. symbol='++', edge_color=self.cursor_color_3D,
  4921. edge_width=self.defaults["global_cursor_width"],
  4922. size=self.defaults["global_cursor_size"])
  4923. else:
  4924. pos = (pos_canvas[0], pos_canvas[1])
  4925. self.dx = pos[0] - float(self.rel_point1[0])
  4926. self.dy = pos[1] - float(self.rel_point1[1])
  4927. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4928. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4929. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4930. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4931. units = self.defaults["units"].lower()
  4932. self.plotcanvas.text_hud.text = \
  4933. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4934. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4935. self.mouse = [pos[0], pos[1]]
  4936. # if the mouse is moved and the LMB is clicked then the action is a selection
  4937. if self.event_is_dragging == 1 and event.button == 1:
  4938. self.delete_selection_shape()
  4939. if self.dx < 0:
  4940. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4941. face_color=self.defaults['global_alt_sel_fill'])
  4942. self.selection_type = False
  4943. elif self.dx >= 0:
  4944. self.draw_moving_selection_shape(self.pos, pos)
  4945. self.selection_type = True
  4946. else:
  4947. self.selection_type = None
  4948. else:
  4949. self.selection_type = None
  4950. # hover effect - enabled in Preferences -> General -> appGUI Settings
  4951. if self.defaults['global_hover']:
  4952. for obj in self.collection.get_list():
  4953. try:
  4954. # select the object(s) only if it is enabled (plotted)
  4955. if obj.options['plot']:
  4956. if obj not in self.collection.get_selected():
  4957. poly_obj = Polygon(
  4958. [(obj.options['xmin'], obj.options['ymin']),
  4959. (obj.options['xmax'], obj.options['ymin']),
  4960. (obj.options['xmax'], obj.options['ymax']),
  4961. (obj.options['xmin'], obj.options['ymax'])]
  4962. )
  4963. if Point(pos).within(poly_obj):
  4964. if obj.isHovering is False:
  4965. obj.isHovering = True
  4966. obj.notHovering = True
  4967. # create the selection box around the selected object
  4968. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4969. else:
  4970. if obj.notHovering is True:
  4971. obj.notHovering = False
  4972. obj.isHovering = False
  4973. self.delete_hover_shape()
  4974. except Exception:
  4975. # the Exception here will happen if we try to select on screen and we have an
  4976. # newly (and empty) just created Geometry or Excellon object that do not have the
  4977. # xmin, xmax, ymin, ymax options.
  4978. # In this case poly_obj creation (see above) will fail
  4979. pass
  4980. except Exception as e:
  4981. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4982. self.ui.position_label.setText("")
  4983. # self.ui.rel_position_label.setText("")
  4984. self.mouse = None
  4985. def on_mouse_click_release_over_plot(self, event):
  4986. """
  4987. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4988. and has been registered in ''self.__init__()''.
  4989. :param event: contains information about the event.
  4990. :return:
  4991. """
  4992. if self.is_legacy is False:
  4993. event_pos = event.pos
  4994. right_button = 2
  4995. else:
  4996. event_pos = (event.xdata, event.ydata)
  4997. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4998. right_button = 3
  4999. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5000. if self.grid_status():
  5001. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5002. else:
  5003. pos = (pos_canvas[0], pos_canvas[1])
  5004. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5005. # canvas menu
  5006. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5007. self.ui.popMenu.mouse_is_panning = False
  5008. self.cursor = QtGui.QCursor()
  5009. self.populate_cmenu_grids()
  5010. self.ui.popMenu.popup(self.cursor.pos())
  5011. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5012. # selection and then select a type of selection ("enclosing" or "touching")
  5013. if event.button == 1: # left click
  5014. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5015. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5016. if modifiers == QtCore.Qt.ShiftModifier:
  5017. # do not auto open the Project Tab
  5018. self.click_noproject = True
  5019. self.clipboard.setText(
  5020. self.defaults["global_point_clipboard_format"] %
  5021. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5022. )
  5023. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5024. return
  5025. if self.doubleclick is True:
  5026. self.doubleclick = False
  5027. if self.collection.get_selected():
  5028. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5029. if self.ui.splitter.sizes()[0] == 0:
  5030. self.ui.splitter.setSizes([1, 1])
  5031. try:
  5032. # delete the selection shape(S) as it may be in the way
  5033. self.delete_selection_shape()
  5034. self.delete_hover_shape()
  5035. except Exception as e:
  5036. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5037. return
  5038. else:
  5039. # WORKAROUND for LEGACY MODE
  5040. if self.is_legacy is True:
  5041. # if there is no move on canvas then we have no dragging selection
  5042. if self.dx == 0 or self.dy == 0:
  5043. self.selection_type = None
  5044. if self.selection_type is not None:
  5045. try:
  5046. self.selection_area_handler(self.pos, pos, self.selection_type)
  5047. self.selection_type = None
  5048. except Exception as e:
  5049. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5050. return
  5051. else:
  5052. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5053. if key_modifier == QtCore.Qt.ShiftModifier:
  5054. mod_key = 'Shift'
  5055. elif key_modifier == QtCore.Qt.ControlModifier:
  5056. mod_key = 'Control'
  5057. else:
  5058. mod_key = None
  5059. try:
  5060. if self.command_active is None:
  5061. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5062. # deselect, and if it's not selected then it will be selected
  5063. # If there is no active command (self.command_active is None) then we check if we clicked
  5064. # on a object by checking the bounding limits against mouse click position
  5065. if mod_key == self.defaults["global_mselect_key"]:
  5066. self.select_objects(key='multisel')
  5067. else:
  5068. # If there is no active command (self.command_active is None) then we check if
  5069. # we clicked on a object by checking the bounding limits against mouse click position
  5070. self.select_objects()
  5071. self.delete_hover_shape()
  5072. except Exception as e:
  5073. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5074. return
  5075. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5076. """
  5077. :param start_pos: mouse position when the selection LMB click was done
  5078. :param end_pos: mouse position when the left mouse button is released
  5079. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5080. :return:
  5081. """
  5082. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5083. # delete previous selection shape
  5084. self.delete_selection_shape()
  5085. # make all objects inactive
  5086. self.collection.set_all_inactive()
  5087. for obj in self.collection.get_list():
  5088. try:
  5089. # select the object(s) only if it is enabled (plotted)
  5090. if obj.options['plot']:
  5091. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5092. (obj.options['xmax'], obj.options['ymin']),
  5093. (obj.options['xmax'], obj.options['ymax']),
  5094. (obj.options['xmin'], obj.options['ymax'])])
  5095. if sel_type is True:
  5096. if poly_obj.within(poly_selection):
  5097. # create the selection box around the selected object
  5098. if self.defaults['global_selection_shape'] is True:
  5099. self.draw_selection_shape(obj)
  5100. self.collection.set_active(obj.options['name'])
  5101. else:
  5102. if poly_selection.intersects(poly_obj):
  5103. # create the selection box around the selected object
  5104. if self.defaults['global_selection_shape'] is True:
  5105. self.draw_selection_shape(obj)
  5106. self.collection.set_active(obj.options['name'])
  5107. obj.selection_shape_drawn = True
  5108. except Exception as e:
  5109. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5110. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5111. # In this case poly_obj creation (see above) will fail
  5112. log.debug("App.selection_area_handler() --> %s" % str(e))
  5113. def select_objects(self, key=None):
  5114. """
  5115. Will select objects clicked on canvas
  5116. :param key: for future use in cumulative selection
  5117. :return:
  5118. """
  5119. # list where we store the overlapped objects under our mouse left click position
  5120. if key is None:
  5121. self.objects_under_the_click_list = []
  5122. # Populate the list with the overlapped objects on the click position
  5123. curr_x, curr_y = self.pos
  5124. for obj in self.all_objects_list:
  5125. # ScriptObject and DocumentObject objects can't be selected
  5126. if obj.kind == 'script' or obj.kind == 'document':
  5127. continue
  5128. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5129. continue
  5130. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5131. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5132. if obj.options['name'] not in self.objects_under_the_click_list:
  5133. if obj.options['plot']:
  5134. # add objects to the objects_under_the_click list only if the object is plotted
  5135. # (active and not disabled)
  5136. self.objects_under_the_click_list.append(obj.options['name'])
  5137. try:
  5138. if self.objects_under_the_click_list:
  5139. curr_sel_obj = self.collection.get_active()
  5140. # case when there is only an object under the click and we toggle it
  5141. if len(self.objects_under_the_click_list) == 1:
  5142. if curr_sel_obj is None:
  5143. self.collection.set_active(self.objects_under_the_click_list[0])
  5144. curr_sel_obj = self.collection.get_active()
  5145. # create the selection box around the selected object
  5146. if self.defaults['global_selection_shape'] is True:
  5147. self.draw_selection_shape(curr_sel_obj)
  5148. curr_sel_obj.selection_shape_drawn = True
  5149. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5150. self.collection.on_objects_selection(False)
  5151. self.delete_selection_shape()
  5152. curr_sel_obj.selection_shape_drawn = False
  5153. self.collection.set_active(self.objects_under_the_click_list[0])
  5154. curr_sel_obj = self.collection.get_active()
  5155. # create the selection box around the selected object
  5156. if self.defaults['global_selection_shape'] is True:
  5157. self.draw_selection_shape(curr_sel_obj)
  5158. curr_sel_obj.selection_shape_drawn = True
  5159. self.selected_message(curr_sel_obj=curr_sel_obj)
  5160. elif curr_sel_obj.selection_shape_drawn is False:
  5161. if self.defaults['global_selection_shape'] is True:
  5162. self.draw_selection_shape(curr_sel_obj)
  5163. curr_sel_obj.selection_shape_drawn = True
  5164. else:
  5165. self.collection.on_objects_selection(False)
  5166. self.delete_selection_shape()
  5167. if self.call_source != 'app':
  5168. self.call_source = 'app'
  5169. self.selected_message(curr_sel_obj=curr_sel_obj)
  5170. else:
  5171. # If there is no selected object
  5172. # make active the first element of the overlapped objects list
  5173. if self.collection.get_active() is None:
  5174. self.collection.set_active(self.objects_under_the_click_list[0])
  5175. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5176. name_sel_obj = self.collection.get_active().options['name']
  5177. # In case that there is a selected object but it is not in the overlapped object list
  5178. # make that object inactive and activate the first element in the overlapped object list
  5179. if name_sel_obj not in self.objects_under_the_click_list:
  5180. self.collection.set_inactive(name_sel_obj)
  5181. name_sel_obj = self.objects_under_the_click_list[0]
  5182. self.collection.set_active(name_sel_obj)
  5183. else:
  5184. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5185. self.collection.set_all_inactive()
  5186. self.collection.set_active(
  5187. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5188. curr_sel_obj = self.collection.get_active()
  5189. # delete the possible selection box around a possible selected object
  5190. self.delete_selection_shape()
  5191. curr_sel_obj.selection_shape_drawn = False
  5192. # create the selection box around the selected object
  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. self.selected_message(curr_sel_obj=curr_sel_obj)
  5197. else:
  5198. # deselect everything
  5199. self.collection.on_objects_selection(False)
  5200. # delete the possible selection box around a possible selected object
  5201. self.delete_selection_shape()
  5202. for o in self.collection.get_list():
  5203. o.selection_shape_drawn = False
  5204. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5205. # only when working on App
  5206. if self.call_source == 'app':
  5207. if self.click_noproject is False:
  5208. # if the Tool Tab is in focus don't change focus to Project Tab
  5209. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5210. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5211. else:
  5212. # restore auto open the Project Tab
  5213. self.click_noproject = False
  5214. # delete any text in the status bar, implicitly the last object name that was selected
  5215. # self.inform.emit("")
  5216. else:
  5217. self.call_source = 'app'
  5218. except Exception as e:
  5219. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5220. def selected_message(self, curr_sel_obj):
  5221. if curr_sel_obj:
  5222. if curr_sel_obj.kind == 'gerber':
  5223. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5224. color='green',
  5225. name=str(curr_sel_obj.options['name']),
  5226. tx=_("selected"))
  5227. )
  5228. elif curr_sel_obj.kind == 'excellon':
  5229. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5230. color='brown',
  5231. name=str(curr_sel_obj.options['name']),
  5232. tx=_("selected"))
  5233. )
  5234. elif curr_sel_obj.kind == 'cncjob':
  5235. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5236. color='blue',
  5237. name=str(curr_sel_obj.options['name']),
  5238. tx=_("selected"))
  5239. )
  5240. elif curr_sel_obj.kind == 'geometry':
  5241. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5242. color='red',
  5243. name=str(curr_sel_obj.options['name']),
  5244. tx=_("selected"))
  5245. )
  5246. def delete_hover_shape(self):
  5247. self.hover_shapes.clear()
  5248. self.hover_shapes.redraw()
  5249. def draw_hover_shape(self, sel_obj, color=None):
  5250. """
  5251. :param sel_obj: The object for which the hover shape must be drawn
  5252. :param color: The color of the hover shape
  5253. :return: None
  5254. """
  5255. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5256. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5257. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5258. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5259. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5260. if self.defaults['units'].upper() == 'MM':
  5261. hover_rect = hover_rect.buffer(-0.1)
  5262. hover_rect = hover_rect.buffer(0.2)
  5263. else:
  5264. hover_rect = hover_rect.buffer(-0.00393)
  5265. hover_rect = hover_rect.buffer(0.00787)
  5266. # if color:
  5267. # face = Color(color)
  5268. # face.alpha = 0.2
  5269. # outline = Color(color, alpha=0.8)
  5270. # else:
  5271. # face = Color(self.defaults['global_sel_fill'])
  5272. # face.alpha = 0.2
  5273. # outline = self.defaults['global_sel_line']
  5274. if color:
  5275. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5276. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5277. else:
  5278. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5279. outline = self.defaults['global_sel_line']
  5280. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5281. if self.is_legacy is True:
  5282. self.hover_shapes.redraw()
  5283. def delete_selection_shape(self):
  5284. self.move_tool.sel_shapes.clear()
  5285. self.move_tool.sel_shapes.redraw()
  5286. def draw_selection_shape(self, sel_obj, color=None):
  5287. """
  5288. Will draw a selection shape around the selected object.
  5289. :param sel_obj: The object for which the selection shape must be drawn
  5290. :param color: The color for the selection shape.
  5291. :return: None
  5292. """
  5293. if sel_obj is None:
  5294. return
  5295. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5296. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5297. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5298. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5299. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5300. if self.defaults['units'].upper() == 'MM':
  5301. sel_rect = sel_rect.buffer(-0.1)
  5302. sel_rect = sel_rect.buffer(0.2)
  5303. else:
  5304. sel_rect = sel_rect.buffer(-0.00393)
  5305. sel_rect = sel_rect.buffer(0.00787)
  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. if self.is_legacy is False:
  5311. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5312. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5313. else:
  5314. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5315. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5316. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5317. color=outline,
  5318. face_color=face,
  5319. update=True,
  5320. layer=0,
  5321. tolerance=None))
  5322. if self.is_legacy is True:
  5323. self.move_tool.sel_shapes.redraw()
  5324. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5325. """
  5326. Will draw a selection shape when dragging mouse on canvas.
  5327. :param old_coords: Old coordinates
  5328. :param coords: New coordinates
  5329. :param kwargs: Keyword arguments
  5330. :return:
  5331. """
  5332. if 'color' in kwargs:
  5333. color = kwargs['color']
  5334. else:
  5335. color = self.defaults['global_sel_line']
  5336. if 'face_color' in kwargs:
  5337. face_color = kwargs['face_color']
  5338. else:
  5339. face_color = self.defaults['global_sel_fill']
  5340. if 'face_alpha' in kwargs:
  5341. face_alpha = kwargs['face_alpha']
  5342. else:
  5343. face_alpha = 0.3
  5344. x0, y0 = old_coords
  5345. x1, y1 = coords
  5346. pt1 = (x0, y0)
  5347. pt2 = (x1, y0)
  5348. pt3 = (x1, y1)
  5349. pt4 = (x0, y1)
  5350. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5351. # color_t = Color(face_color)
  5352. # color_t.alpha = face_alpha
  5353. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5354. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5355. layer=0, tolerance=None)
  5356. if self.is_legacy is True:
  5357. self.move_tool.sel_shapes.redraw()
  5358. def on_file_new_click(self):
  5359. """
  5360. Callback for menu item File -> New.
  5361. Executed on clicking the Menu -> File -> New Project
  5362. :return:
  5363. """
  5364. if self.collection.get_list() and self.should_we_save:
  5365. msgbox = QtWidgets.QMessageBox()
  5366. # msgbox.setText("<B>Save changes ...</B>")
  5367. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5368. "Creating a New project will delete them.\n"
  5369. "Do you want to Save the project?"))
  5370. msgbox.setWindowTitle(_("Save changes"))
  5371. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5372. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5373. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5374. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5375. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5376. msgbox.setDefaultButton(bt_yes)
  5377. msgbox.exec_()
  5378. response = msgbox.clickedButton()
  5379. if response == bt_yes:
  5380. self.on_file_saveprojectas()
  5381. elif response == bt_cancel:
  5382. return
  5383. elif response == bt_no:
  5384. self.on_file_new()
  5385. else:
  5386. self.on_file_new()
  5387. self.inform.emit('[success] %s...' % _("New Project created"))
  5388. def on_file_new(self, cli=None):
  5389. """
  5390. Returns the application to its startup state. This method is thread-safe.
  5391. :param cli: Boolean. If True this method was run from command line
  5392. :return: None
  5393. """
  5394. self.defaults.report_usage("on_file_new")
  5395. # Remove everything from memory
  5396. App.log.debug("on_file_new()")
  5397. # close any editor that might be open
  5398. if self.call_source != 'app':
  5399. self.editor2object(cleanup=True)
  5400. # ## EDITOR section
  5401. self.geo_editor = AppGeoEditor(self)
  5402. self.exc_editor = AppExcEditor(self)
  5403. self.grb_editor = AppGerberEditor(self)
  5404. # Clear pool
  5405. self.clear_pool()
  5406. for obj in self.collection.get_list():
  5407. # delete shapes left drawn from mark shape_collections, if any
  5408. if isinstance(obj, GerberObject):
  5409. try:
  5410. for el in obj.mark_shapes:
  5411. obj.mark_shapes[el].clear(update=True)
  5412. obj.mark_shapes[el].enabled = False
  5413. del el
  5414. except AttributeError:
  5415. pass
  5416. # also delete annotation shapes, if any
  5417. elif isinstance(obj, CNCJobObject):
  5418. try:
  5419. obj.text_col.enabled = False
  5420. del obj.text_col
  5421. obj.annotation.clear(update=True)
  5422. del obj.annotation
  5423. except AttributeError:
  5424. pass
  5425. # delete the exclusion areas
  5426. self.exc_areas.clear_shapes()
  5427. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5428. self.shell.init_tcl()
  5429. # delete any selection shape on canvas
  5430. self.delete_selection_shape()
  5431. # delete all FlatCAM objects
  5432. self.collection.delete_all()
  5433. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5434. self.setup_component_editor()
  5435. # Clear project filename
  5436. self.project_filename = None
  5437. # Load the application defaults
  5438. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5439. # Re-fresh project options
  5440. self.on_options_app2project()
  5441. # Init FlatCAMTools
  5442. self.init_tools()
  5443. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5444. if cli is None:
  5445. # we need to go in reverse because once we remove a tab then the index changes
  5446. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5447. # and so on. Therefore the deletion should be done in reverse
  5448. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5449. for index in range(wdg_count, -1, -1):
  5450. try:
  5451. self.ui.plot_tab_area.closeTab(index)
  5452. except Exception as e:
  5453. log.debug("App.on_file_new() --> %s" % str(e))
  5454. # # And then add again the Plot Area
  5455. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5456. self.ui.plot_tab_area.protectTab(0)
  5457. # take the focus of the Notebook on Project Tab.
  5458. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5459. self.set_ui_title(name=_("New Project - Not saved"))
  5460. def obj_properties(self):
  5461. """
  5462. Will launch the object Properties Tool
  5463. :return:
  5464. """
  5465. self.defaults.report_usage("obj_properties()")
  5466. self.properties_tool.run(toggle=False)
  5467. def on_project_context_save(self):
  5468. """
  5469. Wrapper, will save the object function of it's type
  5470. :return:
  5471. """
  5472. obj = self.collection.get_active()
  5473. if type(obj) == GeometryObject:
  5474. self.on_file_exportdxf()
  5475. elif type(obj) == ExcellonObject:
  5476. self.on_file_saveexcellon()
  5477. elif type(obj) == CNCJobObject:
  5478. obj.on_exportgcode_button_click()
  5479. elif type(obj) == GerberObject:
  5480. self.on_file_savegerber()
  5481. elif type(obj) == ScriptObject:
  5482. self.on_file_savescript()
  5483. elif type(obj) == DocumentObject:
  5484. self.on_file_savedocument()
  5485. def obj_move(self):
  5486. """
  5487. Callback for the Move menu entry in various Context Menu's.
  5488. :return:
  5489. """
  5490. self.defaults.report_usage("obj_move()")
  5491. self.move_tool.run(toggle=False)
  5492. def on_fileopengerber(self, signal, name=None):
  5493. """
  5494. File menu callback for opening a Gerber.
  5495. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5496. :param name:
  5497. :return: None
  5498. """
  5499. self.defaults.report_usage("on_fileopengerber")
  5500. App.log.debug("on_fileopengerber()")
  5501. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5502. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5503. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5504. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5505. "*.outline);;" \
  5506. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5507. "*.mil);;" \
  5508. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5509. "Allegro Files (*.art);;" \
  5510. "Mentor Files (*.pho *.gdo);;" \
  5511. "All Files (*.*)"
  5512. if name is None:
  5513. try:
  5514. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5515. directory=self.get_last_folder(),
  5516. filter=_filter_,
  5517. initialFilter=self.last_op_gerber_filter)
  5518. except TypeError:
  5519. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5520. filenames = [str(filename) for filename in filenames]
  5521. self.last_op_gerber_filter = _f
  5522. else:
  5523. filenames = [name]
  5524. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5525. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5526. _("Opening Gerber file.")),
  5527. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5528. color=QtGui.QColor("gray"))
  5529. if len(filenames) == 0:
  5530. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5531. else:
  5532. for filename in filenames:
  5533. if filename != '':
  5534. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5535. def on_fileopenexcellon(self, signal, name=None):
  5536. """
  5537. File menu callback for opening an Excellon file.
  5538. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5539. :param name:
  5540. :return: None
  5541. """
  5542. self.defaults.report_usage("on_fileopenexcellon")
  5543. App.log.debug("on_fileopenexcellon()")
  5544. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5545. "All Files (*.*)"
  5546. if name is None:
  5547. try:
  5548. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5549. directory=self.get_last_folder(),
  5550. filter=_filter_,
  5551. initialFilter=self.last_op_excellon_filter)
  5552. except TypeError:
  5553. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5554. filenames = [str(filename) for filename in filenames]
  5555. self.last_op_excellon_filter = _f
  5556. else:
  5557. filenames = [str(name)]
  5558. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5559. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5560. _("Opening Excellon file.")),
  5561. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5562. color=QtGui.QColor("gray"))
  5563. if len(filenames) == 0:
  5564. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5565. else:
  5566. for filename in filenames:
  5567. if filename != '':
  5568. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5569. def on_fileopengcode(self, signal, name=None):
  5570. """
  5571. File menu call back for opening gcode.
  5572. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5573. :param name:
  5574. :return:
  5575. """
  5576. self.defaults.report_usage("on_fileopengcode")
  5577. App.log.debug("on_fileopengcode()")
  5578. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5579. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5580. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5581. "All Files (*.*)"
  5582. if name is None:
  5583. try:
  5584. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5585. directory=self.get_last_folder(),
  5586. filter=_filter_,
  5587. initialFilter=self.last_op_gcode_filter)
  5588. except TypeError:
  5589. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5590. filenames = [str(filename) for filename in filenames]
  5591. self.last_op_gcode_filter = _f
  5592. else:
  5593. filenames = [name]
  5594. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5595. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5596. _("Opening G-Code file.")),
  5597. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5598. color=QtGui.QColor("gray"))
  5599. if len(filenames) == 0:
  5600. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5601. else:
  5602. for filename in filenames:
  5603. if filename != '':
  5604. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5605. def on_file_openproject(self, signal):
  5606. """
  5607. File menu callback for opening a project.
  5608. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5609. :return: None
  5610. """
  5611. self.defaults.report_usage("on_file_openproject")
  5612. App.log.debug("on_file_openproject()")
  5613. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5614. try:
  5615. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5616. directory=self.get_last_folder(), filter=_filter_)
  5617. except TypeError:
  5618. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5619. # The Qt methods above will return a QString which can cause problems later.
  5620. # So far json.dump() will fail to serialize it.
  5621. # TODO: Improve the serialization methods and remove this fix.
  5622. filename = str(filename)
  5623. if filename == "":
  5624. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5625. else:
  5626. # self.worker_task.emit({'fcn': self.open_project,
  5627. # 'params': [filename]})
  5628. # The above was failing because open_project() is not
  5629. # thread safe. The new_project()
  5630. self.open_project(filename)
  5631. def on_fileopenhpgl2(self, signal, name=None):
  5632. """
  5633. File menu callback for opening a HPGL2.
  5634. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5635. :param name:
  5636. :return: None
  5637. """
  5638. self.defaults.report_usage("on_fileopenhpgl2")
  5639. App.log.debug("on_fileopenhpgl2()")
  5640. _filter_ = "HPGL2 Files (*.plt);;" \
  5641. "All Files (*.*)"
  5642. if name is None:
  5643. try:
  5644. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5645. directory=self.get_last_folder(),
  5646. filter=_filter_)
  5647. except TypeError:
  5648. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5649. filenames = [str(filename) for filename in filenames]
  5650. else:
  5651. filenames = [name]
  5652. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5653. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5654. _("Opening HPGL2 file.")),
  5655. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5656. color=QtGui.QColor("gray"))
  5657. if len(filenames) == 0:
  5658. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5659. else:
  5660. for filename in filenames:
  5661. if filename != '':
  5662. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5663. def on_file_openconfig(self, signal):
  5664. """
  5665. File menu callback for opening a config file.
  5666. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5667. :return: None
  5668. """
  5669. self.defaults.report_usage("on_file_openconfig")
  5670. App.log.debug("on_file_openconfig()")
  5671. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5672. try:
  5673. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5674. directory=self.data_path, filter=_filter_)
  5675. except TypeError:
  5676. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5677. filter=_filter_)
  5678. if filename == "":
  5679. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5680. else:
  5681. self.open_config_file(filename)
  5682. def on_file_exportsvg(self):
  5683. """
  5684. Callback for menu item File->Export SVG.
  5685. :return: None
  5686. """
  5687. self.defaults.report_usage("on_file_exportsvg")
  5688. App.log.debug("on_file_exportsvg()")
  5689. obj = self.collection.get_active()
  5690. if obj is None:
  5691. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5692. msg = _("Please Select a Geometry object to export")
  5693. msgbox = QtWidgets.QMessageBox()
  5694. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5695. msgbox.setInformativeText(msg)
  5696. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5697. msgbox.setDefaultButton(bt_ok)
  5698. msgbox.exec_()
  5699. return
  5700. # Check for more compatible types and add as required
  5701. if (not isinstance(obj, GeometryObject)
  5702. and not isinstance(obj, GerberObject)
  5703. and not isinstance(obj, CNCJobObject)
  5704. and not isinstance(obj, ExcellonObject)):
  5705. msg = '[ERROR_NOTCL] %s' % \
  5706. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5707. msgbox = QtWidgets.QMessageBox()
  5708. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5709. msgbox.setInformativeText(msg)
  5710. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5711. msgbox.setDefaultButton(bt_ok)
  5712. msgbox.exec_()
  5713. return
  5714. name = obj.options["name"]
  5715. _filter = "SVG File (*.svg);;All Files (*.*)"
  5716. try:
  5717. filename, _f = FCFileSaveDialog.get_saved_filename(
  5718. caption=_("Export SVG"),
  5719. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5720. ext_filter=_filter)
  5721. except TypeError:
  5722. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5723. filename = str(filename)
  5724. if filename == "":
  5725. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5726. return
  5727. else:
  5728. self.export_svg(name, filename)
  5729. if self.defaults["global_open_style"] is False:
  5730. self.file_opened.emit("SVG", filename)
  5731. self.file_saved.emit("SVG", filename)
  5732. def on_file_exportpng(self):
  5733. self.defaults.report_usage("on_file_exportpng")
  5734. App.log.debug("on_file_exportpng()")
  5735. self.date = str(datetime.today()).rpartition('.')[0]
  5736. self.date = ''.join(c for c in self.date if c not in ':-')
  5737. self.date = self.date.replace(' ', '_')
  5738. data = None
  5739. if self.is_legacy is False:
  5740. image = _screenshot(alpha=False)
  5741. data = np.asarray(image)
  5742. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5743. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5744. return
  5745. filter_ = "PNG File (*.png);;All Files (*.*)"
  5746. try:
  5747. filename, _f = FCFileSaveDialog.get_saved_filename(
  5748. caption=_("Export PNG Image"),
  5749. directory=self.get_last_save_folder() + '/png_' + self.date,
  5750. ext_filter=filter_)
  5751. except TypeError:
  5752. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5753. filename = str(filename)
  5754. if filename == "":
  5755. self.inform.emit(_("Cancelled."))
  5756. return
  5757. else:
  5758. if self.is_legacy is False:
  5759. write_png(filename, data)
  5760. else:
  5761. self.plotcanvas.figure.savefig(filename)
  5762. if self.defaults["global_open_style"] is False:
  5763. self.file_opened.emit("png", filename)
  5764. self.file_saved.emit("png", filename)
  5765. def on_file_savegerber(self):
  5766. """
  5767. Callback for menu item in Project context menu.
  5768. :return: None
  5769. """
  5770. self.defaults.report_usage("on_file_savegerber")
  5771. App.log.debug("on_file_savegerber()")
  5772. obj = self.collection.get_active()
  5773. if obj is None:
  5774. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5775. return
  5776. # Check for more compatible types and add as required
  5777. if not isinstance(obj, GerberObject):
  5778. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5779. return
  5780. name = self.collection.get_active().options["name"]
  5781. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5782. try:
  5783. filename, _f = FCFileSaveDialog.get_saved_filename(
  5784. caption="Save Gerber source file",
  5785. directory=self.get_last_save_folder() + '/' + name,
  5786. ext_filter=_filter)
  5787. except TypeError:
  5788. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5789. filename = str(filename)
  5790. if filename == "":
  5791. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5792. return
  5793. else:
  5794. self.save_source_file(name, filename)
  5795. if self.defaults["global_open_style"] is False:
  5796. self.file_opened.emit("Gerber", filename)
  5797. self.file_saved.emit("Gerber", filename)
  5798. def on_file_savescript(self):
  5799. """
  5800. Callback for menu item in Project context menu.
  5801. :return: None
  5802. """
  5803. self.defaults.report_usage("on_file_savescript")
  5804. App.log.debug("on_file_savescript()")
  5805. obj = self.collection.get_active()
  5806. if obj is None:
  5807. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5808. return
  5809. # Check for more compatible types and add as required
  5810. if not isinstance(obj, ScriptObject):
  5811. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5812. return
  5813. name = self.collection.get_active().options["name"]
  5814. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5815. try:
  5816. filename, _f = FCFileSaveDialog.get_saved_filename(
  5817. caption="Save Script source file",
  5818. directory=self.get_last_save_folder() + '/' + name,
  5819. ext_filter=_filter)
  5820. except TypeError:
  5821. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5822. filename = str(filename)
  5823. if filename == "":
  5824. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5825. return
  5826. else:
  5827. self.save_source_file(name, filename)
  5828. if self.defaults["global_open_style"] is False:
  5829. self.file_opened.emit("Script", filename)
  5830. self.file_saved.emit("Script", filename)
  5831. def on_file_savedocument(self):
  5832. """
  5833. Callback for menu item in Project context menu.
  5834. :return: None
  5835. """
  5836. self.defaults.report_usage("on_file_savedocument")
  5837. App.log.debug("on_file_savedocument()")
  5838. obj = self.collection.get_active()
  5839. if obj is None:
  5840. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5841. return
  5842. # Check for more compatible types and add as required
  5843. if not isinstance(obj, ScriptObject):
  5844. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5845. return
  5846. name = self.collection.get_active().options["name"]
  5847. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5848. try:
  5849. filename, _f = FCFileSaveDialog.get_saved_filename(
  5850. caption="Save Document source file",
  5851. directory=self.get_last_save_folder() + '/' + name,
  5852. ext_filter=_filter)
  5853. except TypeError:
  5854. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5855. ext_filter=_filter)
  5856. filename = str(filename)
  5857. if filename == "":
  5858. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5859. return
  5860. else:
  5861. self.save_source_file(name, filename)
  5862. if self.defaults["global_open_style"] is False:
  5863. self.file_opened.emit("Document", filename)
  5864. self.file_saved.emit("Document", filename)
  5865. def on_file_saveexcellon(self):
  5866. """
  5867. Callback for menu item in project context menu.
  5868. :return: None
  5869. """
  5870. self.defaults.report_usage("on_file_saveexcellon")
  5871. App.log.debug("on_file_saveexcellon()")
  5872. obj = self.collection.get_active()
  5873. if obj is None:
  5874. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5875. return
  5876. # Check for more compatible types and add as required
  5877. if not isinstance(obj, ExcellonObject):
  5878. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5879. return
  5880. name = self.collection.get_active().options["name"]
  5881. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5882. try:
  5883. filename, _f = FCFileSaveDialog.get_saved_filename(
  5884. caption=_("Save Excellon source file"),
  5885. directory=self.get_last_save_folder() + '/' + name,
  5886. ext_filter=_filter)
  5887. except TypeError:
  5888. filename, _f = FCFileSaveDialog.get_saved_filename(
  5889. caption=_("Save Excellon source file"), ext_filter=_filter)
  5890. filename = str(filename)
  5891. if filename == "":
  5892. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5893. return
  5894. else:
  5895. self.save_source_file(name, filename)
  5896. if self.defaults["global_open_style"] is False:
  5897. self.file_opened.emit("Excellon", filename)
  5898. self.file_saved.emit("Excellon", filename)
  5899. def on_file_exportexcellon(self):
  5900. """
  5901. Callback for menu item File->Export->Excellon.
  5902. :return: None
  5903. """
  5904. self.defaults.report_usage("on_file_exportexcellon")
  5905. App.log.debug("on_file_exportexcellon()")
  5906. obj = self.collection.get_active()
  5907. if obj is None:
  5908. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5909. return
  5910. # Check for more compatible types and add as required
  5911. if not isinstance(obj, ExcellonObject):
  5912. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5913. return
  5914. name = self.collection.get_active().options["name"]
  5915. _filter = self.defaults["excellon_save_filters"]
  5916. try:
  5917. filename, _f = FCFileSaveDialog.get_saved_filename(
  5918. caption=_("Export Excellon"),
  5919. directory=self.get_last_save_folder() + '/' + name,
  5920. ext_filter=_filter)
  5921. except TypeError:
  5922. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5923. filename = str(filename)
  5924. if filename == "":
  5925. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5926. return
  5927. else:
  5928. used_extension = filename.rpartition('.')[2]
  5929. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5930. self.export_excellon(name, filename)
  5931. if self.defaults["global_open_style"] is False:
  5932. self.file_opened.emit("Excellon", filename)
  5933. self.file_saved.emit("Excellon", filename)
  5934. def on_file_exportgerber(self):
  5935. """
  5936. Callback for menu item File->Export->Gerber.
  5937. :return: None
  5938. """
  5939. self.defaults.report_usage("on_file_exportgerber")
  5940. App.log.debug("on_file_exportgerber()")
  5941. obj = self.collection.get_active()
  5942. if obj is None:
  5943. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5944. return
  5945. # Check for more compatible types and add as required
  5946. if not isinstance(obj, GerberObject):
  5947. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5948. return
  5949. name = self.collection.get_active().options["name"]
  5950. _filter_ = self.defaults['gerber_save_filters']
  5951. try:
  5952. filename, _f = FCFileSaveDialog.get_saved_filename(
  5953. caption=_("Export Gerber"),
  5954. directory=self.get_last_save_folder() + '/' + name,
  5955. ext_filter=_filter_)
  5956. except TypeError:
  5957. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5958. filename = str(filename)
  5959. if filename == "":
  5960. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5961. return
  5962. else:
  5963. used_extension = filename.rpartition('.')[2]
  5964. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5965. self.export_gerber(name, filename)
  5966. if self.defaults["global_open_style"] is False:
  5967. self.file_opened.emit("Gerber", filename)
  5968. self.file_saved.emit("Gerber", filename)
  5969. def on_file_exportdxf(self):
  5970. """
  5971. Callback for menu item File->Export DXF.
  5972. :return: None
  5973. """
  5974. self.defaults.report_usage("on_file_exportdxf")
  5975. App.log.debug("on_file_exportdxf()")
  5976. obj = self.collection.get_active()
  5977. if obj is None:
  5978. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5979. msg = _("Please Select a Geometry object to export")
  5980. msgbox = QtWidgets.QMessageBox()
  5981. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5982. msgbox.setInformativeText(msg)
  5983. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5984. msgbox.setDefaultButton(bt_ok)
  5985. msgbox.exec_()
  5986. return
  5987. # Check for more compatible types and add as required
  5988. if not isinstance(obj, GeometryObject):
  5989. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5990. msgbox = QtWidgets.QMessageBox()
  5991. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5992. msgbox.setInformativeText(msg)
  5993. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5994. msgbox.setDefaultButton(bt_ok)
  5995. msgbox.exec_()
  5996. return
  5997. name = self.collection.get_active().options["name"]
  5998. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5999. try:
  6000. filename, _f = FCFileSaveDialog.get_saved_filename(
  6001. caption=_("Export DXF"),
  6002. directory=self.get_last_save_folder() + '/' + name,
  6003. ext_filter=_filter_)
  6004. except TypeError:
  6005. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6006. filename = str(filename)
  6007. if filename == "":
  6008. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6009. return
  6010. else:
  6011. self.export_dxf(name, filename)
  6012. if self.defaults["global_open_style"] is False:
  6013. self.file_opened.emit("DXF", filename)
  6014. self.file_saved.emit("DXF", filename)
  6015. def on_file_importsvg(self, type_of_obj):
  6016. """
  6017. Callback for menu item File->Import SVG.
  6018. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6019. :type type_of_obj: str
  6020. :return: None
  6021. """
  6022. self.defaults.report_usage("on_file_importsvg")
  6023. App.log.debug("on_file_importsvg()")
  6024. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6025. try:
  6026. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6027. directory=self.get_last_folder(), filter=_filter_)
  6028. except TypeError:
  6029. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6030. filter=_filter_)
  6031. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6032. type_of_obj = "geometry"
  6033. filenames = [str(filename) for filename in filenames]
  6034. if len(filenames) == 0:
  6035. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6036. else:
  6037. for filename in filenames:
  6038. if filename != '':
  6039. self.worker_task.emit({'fcn': self.import_svg,
  6040. 'params': [filename, type_of_obj]})
  6041. def on_file_importdxf(self, type_of_obj):
  6042. """
  6043. Callback for menu item File->Import DXF.
  6044. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6045. :type type_of_obj: str
  6046. :return: None
  6047. """
  6048. self.defaults.report_usage("on_file_importdxf")
  6049. App.log.debug("on_file_importdxf()")
  6050. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6051. try:
  6052. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6053. directory=self.get_last_folder(),
  6054. filter=_filter_)
  6055. except TypeError:
  6056. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6057. filter=_filter_)
  6058. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6059. type_of_obj = "geometry"
  6060. filenames = [str(filename) for filename in filenames]
  6061. if len(filenames) == 0:
  6062. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6063. else:
  6064. for filename in filenames:
  6065. if filename != '':
  6066. self.worker_task.emit({'fcn': self.import_dxf,
  6067. 'params': [filename, type_of_obj]})
  6068. # ###############################################################################################################
  6069. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6070. # ###############################################################################################################
  6071. def init_code_editor(self, name):
  6072. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6073. # add the tab if it was closed
  6074. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6075. self.text_editor_tab.setObjectName('text_editor_tab')
  6076. # delete the absolute and relative position and messages in the infobar
  6077. self.ui.position_label.setText("")
  6078. # self.ui.rel_position_label.setText("")
  6079. # first clear previous text in text editor (if any)
  6080. self.text_editor_tab.code_editor.clear()
  6081. self.text_editor_tab.code_editor.setReadOnly(False)
  6082. self.toggle_codeeditor = True
  6083. self.text_editor_tab.code_editor.completer_enable = False
  6084. self.text_editor_tab.buttonRun.hide()
  6085. # make sure to keep a reference to the code editor
  6086. self.reference_code_editor = self.text_editor_tab.code_editor
  6087. # Switch plot_area to CNCJob tab
  6088. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6089. def on_view_source(self):
  6090. """
  6091. Called when the user wants to see the source file of the selected object
  6092. :return:
  6093. """
  6094. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6095. self.proc_container.view.set_busy(_("Loading..."))
  6096. try:
  6097. obj = self.collection.get_active()
  6098. except Exception as e:
  6099. log.debug("App.on_view_source() --> %s" % str(e))
  6100. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6101. return 'fail'
  6102. if obj is None:
  6103. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6104. return 'fail'
  6105. flt = "All Files (*.*)"
  6106. if obj.kind == 'gerber':
  6107. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6108. elif obj.kind == 'excellon':
  6109. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6110. elif obj.kind == 'cncjob':
  6111. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6112. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6113. # add the tab if it was closed
  6114. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6115. self.source_editor_tab.setObjectName('source_editor_tab')
  6116. # delete the absolute and relative position and messages in the infobar
  6117. self.ui.position_label.setText("")
  6118. # self.ui.rel_position_label.setText("")
  6119. # first clear previous text in text editor (if any)
  6120. self.source_editor_tab.code_editor.clear()
  6121. self.source_editor_tab.code_editor.setReadOnly(False)
  6122. self.source_editor_tab.code_editor.completer_enable = False
  6123. self.source_editor_tab.buttonRun.hide()
  6124. # Switch plot_area to CNCJob tab
  6125. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6126. try:
  6127. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6128. except TypeError:
  6129. pass
  6130. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6131. try:
  6132. self.source_editor_tab.buttonSave.clicked.disconnect()
  6133. except TypeError:
  6134. pass
  6135. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6136. # then append the text from GCode to the text editor
  6137. if obj.kind == 'cncjob':
  6138. try:
  6139. file = obj.export_gcode(
  6140. preamble=self.defaults["cncjob_prepend"],
  6141. postamble=self.defaults["cncjob_append"],
  6142. to_file=True)
  6143. if file == 'fail':
  6144. return 'fail'
  6145. except AttributeError:
  6146. self.inform.emit('[WARNING_NOTCL] %s' %
  6147. _("There is no selected object for which to see it's source file code."))
  6148. return 'fail'
  6149. else:
  6150. try:
  6151. file = StringIO(obj.source_file)
  6152. except (AttributeError, TypeError):
  6153. self.inform.emit('[WARNING_NOTCL] %s' %
  6154. _("There is no selected object for which to see it's source file code."))
  6155. return 'fail'
  6156. self.source_editor_tab.t_frame.hide()
  6157. try:
  6158. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6159. # for line in file:
  6160. # QtWidgets.QApplication.processEvents()
  6161. # proc_line = str(line).strip('\n')
  6162. # self.source_editor_tab.code_editor.append(proc_line)
  6163. except Exception as e:
  6164. log.debug('App.on_view_source() -->%s' % str(e))
  6165. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6166. return
  6167. self.source_editor_tab.handleTextChanged()
  6168. self.source_editor_tab.t_frame.show()
  6169. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6170. self.proc_container.view.set_idle()
  6171. # self.ui.show()
  6172. def on_toggle_code_editor(self):
  6173. self.defaults.report_usage("on_toggle_code_editor()")
  6174. if self.toggle_codeeditor is False:
  6175. self.init_code_editor(name=_("Code Editor"))
  6176. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6177. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6178. self.text_editor_tab.buttonSave.clicked.disconnect()
  6179. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6180. else:
  6181. for idx in range(self.ui.plot_tab_area.count()):
  6182. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6183. self.ui.plot_tab_area.closeTab(idx)
  6184. break
  6185. self.toggle_codeeditor = False
  6186. def on_code_editor_close(self):
  6187. self.toggle_codeeditor = False
  6188. def goto_text_line(self):
  6189. """
  6190. Will scroll a text to the specified text line.
  6191. :return: None
  6192. """
  6193. dia_box = Dialog_box(title=_("Go to Line ..."),
  6194. label=_("Line:"),
  6195. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6196. initial_text='')
  6197. try:
  6198. line = int(dia_box.location) - 1
  6199. except (ValueError, TypeError):
  6200. line = 0
  6201. if dia_box.ok:
  6202. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6203. # at the top of the window
  6204. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6205. # get the document() of the AppTextEditor
  6206. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6207. # create a Text Cursor based on the searched line
  6208. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6209. # set cursor of the code editor with the cursor at the searcehd line
  6210. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6211. def on_filenewscript(self, silent=False):
  6212. """
  6213. Will create a new script file and open it in the Code Editor
  6214. :param silent: if True will not display status messages
  6215. :return: None
  6216. """
  6217. if silent is False:
  6218. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6219. # delete the absolute and relative position and messages in the infobar
  6220. self.ui.position_label.setText("")
  6221. # self.ui.rel_position_label.setText("")
  6222. self.app_obj.new_script_object()
  6223. # script_text = script_obj.source_file
  6224. #
  6225. # self.proc_container.view.set_busy(_("Loading..."))
  6226. # script_obj.script_editor_tab.t_frame.hide()
  6227. #
  6228. # script_obj.script_editor_tab.t_frame.show()
  6229. # self.proc_container.view.set_idle()
  6230. def on_fileopenscript(self, name=None, silent=False):
  6231. """
  6232. Will open a Tcl script file into the Code Editor
  6233. :param silent: if True will not display status messages
  6234. :param name: name of a Tcl script file to open
  6235. :return: None
  6236. """
  6237. self.defaults.report_usage("on_fileopenscript")
  6238. App.log.debug("on_fileopenscript()")
  6239. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6240. "All Files (*.*)"
  6241. if name:
  6242. filenames = [name]
  6243. else:
  6244. try:
  6245. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6246. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6247. except TypeError:
  6248. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6249. if len(filenames) == 0:
  6250. if silent is False:
  6251. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6252. else:
  6253. for filename in filenames:
  6254. if filename != '':
  6255. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6256. def on_fileopenscript_example(self, name=None, silent=False):
  6257. """
  6258. Will open a Tcl script file into the Code Editor
  6259. :param silent: if True will not display status messages
  6260. :param name: name of a Tcl script file to open
  6261. :return:
  6262. """
  6263. self.defaults.report_usage("on_fileopenscript_example")
  6264. log.debug("on_fileopenscript_example()")
  6265. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6266. "All Files (*.*)"
  6267. # test if the app was frozen and choose the path for the configuration file
  6268. if getattr(sys, "frozen", False) is True:
  6269. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6270. else:
  6271. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6272. if name:
  6273. filenames = [name]
  6274. else:
  6275. try:
  6276. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6277. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6278. except TypeError:
  6279. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6280. if len(filenames) == 0:
  6281. if silent is False:
  6282. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6283. else:
  6284. for filename in filenames:
  6285. if filename != '':
  6286. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6287. def on_filerunscript(self, name=None, silent=False):
  6288. """
  6289. File menu callback for loading and running a TCL script.
  6290. :param silent: if True will not display status messages
  6291. :param name: name of a Tcl script file to be run by FlatCAM
  6292. :return: None
  6293. """
  6294. self.defaults.report_usage("on_filerunscript")
  6295. App.log.debug("on_file_runscript()")
  6296. if name:
  6297. filename = name
  6298. if self.cmd_line_headless != 1:
  6299. self.splash.showMessage('%s: %ssec\n%s' %
  6300. (_("Canvas initialization started.\n"
  6301. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6302. _("Executing ScriptObject file.")
  6303. ),
  6304. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6305. color=QtGui.QColor("gray"))
  6306. else:
  6307. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6308. "All Files (*.*)"
  6309. try:
  6310. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6311. directory=self.get_last_folder(), filter=_filter_)
  6312. except TypeError:
  6313. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6314. # The Qt methods above will return a QString which can cause problems later.
  6315. # So far json.dump() will fail to serialize it.
  6316. filename = str(filename)
  6317. if filename == "":
  6318. if silent is False:
  6319. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6320. else:
  6321. if self.cmd_line_headless != 1:
  6322. if self.ui.shell_dock.isHidden():
  6323. self.ui.shell_dock.show()
  6324. try:
  6325. with open(filename, "r") as tcl_script:
  6326. cmd_line_shellfile_content = tcl_script.read()
  6327. if self.cmd_line_headless != 1:
  6328. self.shell.exec_command(cmd_line_shellfile_content)
  6329. else:
  6330. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6331. if silent is False:
  6332. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6333. except Exception as e:
  6334. log.debug("App.on_filerunscript() -> %s" % str(e))
  6335. sys.exit(2)
  6336. def on_file_saveproject(self, silent=False):
  6337. """
  6338. Callback for menu item File->Save Project. Saves the project to
  6339. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6340. if set to None. The project is saved by calling ``self.save_project()``.
  6341. :param silent: if True will not display status messages
  6342. :return: None
  6343. """
  6344. self.defaults.report_usage("on_file_saveproject")
  6345. if self.project_filename is None:
  6346. self.on_file_saveprojectas()
  6347. else:
  6348. self.worker_task.emit({'fcn': self.save_project,
  6349. 'params': [self.project_filename, silent]})
  6350. if self.defaults["global_open_style"] is False:
  6351. self.file_opened.emit("project", self.project_filename)
  6352. self.file_saved.emit("project", self.project_filename)
  6353. self.set_ui_title(name=self.project_filename)
  6354. self.should_we_save = False
  6355. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6356. """
  6357. Callback for menu item File->Save Project As... Opens a file
  6358. chooser and saves the project to the given file via
  6359. ``self.save_project()``.
  6360. :param make_copy if to be create a copy of the project; boolean
  6361. :param use_thread: if to be run in a separate thread; boolean
  6362. :param quit_action: if to be followed by quiting the application; boolean
  6363. :return: None
  6364. """
  6365. self.defaults.report_usage("on_file_saveprojectas")
  6366. self.date = str(datetime.today()).rpartition('.')[0]
  6367. self.date = ''.join(c for c in self.date if c not in ':-')
  6368. self.date = self.date.replace(' ', '_')
  6369. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6370. try:
  6371. filename, _f = FCFileSaveDialog.get_saved_filename(
  6372. caption=_("Save Project As ..."),
  6373. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6374. proj=_("Project")),
  6375. ext_filter=filter_
  6376. )
  6377. except TypeError:
  6378. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6379. filename = str(filename)
  6380. if filename == '':
  6381. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6382. return
  6383. if use_thread is True:
  6384. self.worker_task.emit({'fcn': self.save_project,
  6385. 'params': [filename, quit_action]})
  6386. else:
  6387. self.save_project(filename, quit_action)
  6388. # self.save_project(filename)
  6389. if self.defaults["global_open_style"] is False:
  6390. self.file_opened.emit("project", filename)
  6391. self.file_saved.emit("project", filename)
  6392. if not make_copy:
  6393. self.project_filename = filename
  6394. self.set_ui_title(name=self.project_filename)
  6395. self.should_we_save = False
  6396. def on_file_save_objects_pdf(self, use_thread=True):
  6397. self.date = str(datetime.today()).rpartition('.')[0]
  6398. self.date = ''.join(c for c in self.date if c not in ':-')
  6399. self.date = self.date.replace(' ', '_')
  6400. try:
  6401. obj_selection = self.collection.get_selected()
  6402. if len(obj_selection) == 1:
  6403. obj_name = str(obj_selection[0].options['name'])
  6404. else:
  6405. obj_name = _("FlatCAM objects print")
  6406. except AttributeError as err:
  6407. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6408. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6409. return
  6410. if not obj_selection:
  6411. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6412. return
  6413. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6414. try:
  6415. filename, _f = FCFileSaveDialog.get_saved_filename(
  6416. caption=_("Save Object as PDF ..."),
  6417. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6418. obj_name=obj_name,
  6419. date=self.date),
  6420. ext_filter=filter_
  6421. )
  6422. except TypeError:
  6423. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6424. filename = str(filename)
  6425. if filename == '':
  6426. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6427. return
  6428. if use_thread is True:
  6429. self.proc_container.new(_("Printing PDF ... Please wait."))
  6430. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6431. else:
  6432. self.save_pdf(filename, obj_selection)
  6433. # self.save_project(filename)
  6434. if self.defaults["global_open_style"] is False:
  6435. self.file_opened.emit("pdf", filename)
  6436. self.file_saved.emit("pdf", filename)
  6437. def save_pdf(self, file_name, obj_selection):
  6438. p_size = self.defaults['global_workspaceT']
  6439. orientation = self.defaults['global_workspace_orientation']
  6440. color = 'black'
  6441. transparency_level = 1.0
  6442. self.pagesize = {}
  6443. self.pagesize.update(
  6444. {
  6445. 'Bounds': None,
  6446. 'A0': (841 * mm, 1189 * mm),
  6447. 'A1': (594 * mm, 841 * mm),
  6448. 'A2': (420 * mm, 594 * mm),
  6449. 'A3': (297 * mm, 420 * mm),
  6450. 'A4': (210 * mm, 297 * mm),
  6451. 'A5': (148 * mm, 210 * mm),
  6452. 'A6': (105 * mm, 148 * mm),
  6453. 'A7': (74 * mm, 105 * mm),
  6454. 'A8': (52 * mm, 74 * mm),
  6455. 'A9': (37 * mm, 52 * mm),
  6456. 'A10': (26 * mm, 37 * mm),
  6457. 'B0': (1000 * mm, 1414 * mm),
  6458. 'B1': (707 * mm, 1000 * mm),
  6459. 'B2': (500 * mm, 707 * mm),
  6460. 'B3': (353 * mm, 500 * mm),
  6461. 'B4': (250 * mm, 353 * mm),
  6462. 'B5': (176 * mm, 250 * mm),
  6463. 'B6': (125 * mm, 176 * mm),
  6464. 'B7': (88 * mm, 125 * mm),
  6465. 'B8': (62 * mm, 88 * mm),
  6466. 'B9': (44 * mm, 62 * mm),
  6467. 'B10': (31 * mm, 44 * mm),
  6468. 'C0': (917 * mm, 1297 * mm),
  6469. 'C1': (648 * mm, 917 * mm),
  6470. 'C2': (458 * mm, 648 * mm),
  6471. 'C3': (324 * mm, 458 * mm),
  6472. 'C4': (229 * mm, 324 * mm),
  6473. 'C5': (162 * mm, 229 * mm),
  6474. 'C6': (114 * mm, 162 * mm),
  6475. 'C7': (81 * mm, 114 * mm),
  6476. 'C8': (57 * mm, 81 * mm),
  6477. 'C9': (40 * mm, 57 * mm),
  6478. 'C10': (28 * mm, 40 * mm),
  6479. # American paper sizes
  6480. 'LETTER': (8.5 * inch, 11 * inch),
  6481. 'LEGAL': (8.5 * inch, 14 * inch),
  6482. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6483. # From https://en.wikipedia.org/wiki/Paper_size
  6484. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6485. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6486. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6487. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6488. 'LEDGER': (17 * inch, 11 * inch),
  6489. }
  6490. )
  6491. exported_svg = []
  6492. for obj in obj_selection:
  6493. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6494. scale_factor_x=None, scale_factor_y=None,
  6495. skew_factor_x=None, skew_factor_y=None,
  6496. mirror=None)
  6497. if obj.kind.lower() == 'gerber':
  6498. # color = self.defaults["gerber_plot_fill"][:-2]
  6499. color = obj.fill_color[:-2]
  6500. elif obj.kind.lower() == 'excellon':
  6501. color = '#C40000'
  6502. elif obj.kind.lower() == 'geometry':
  6503. color = self.defaults["global_draw_color"]
  6504. # Change the attributes of the exported SVG
  6505. # We don't need stroke-width
  6506. # We set opacity to maximum
  6507. # We set the colour to WHITE
  6508. root = ET.fromstring(svg_obj)
  6509. for child in root:
  6510. child.set('fill', str(color))
  6511. child.set('opacity', str(transparency_level))
  6512. child.set('stroke', str(color))
  6513. exported_svg.append(ET.tostring(root))
  6514. xmin = Inf
  6515. ymin = Inf
  6516. xmax = -Inf
  6517. ymax = -Inf
  6518. for obj in obj_selection:
  6519. try:
  6520. gxmin, gymin, gxmax, gymax = obj.bounds()
  6521. xmin = min([xmin, gxmin])
  6522. ymin = min([ymin, gymin])
  6523. xmax = max([xmax, gxmax])
  6524. ymax = max([ymax, gymax])
  6525. except Exception as e:
  6526. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6527. # Determine bounding area for svg export
  6528. bounds = [xmin, ymin, xmax, ymax]
  6529. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6530. # This contain the measure units
  6531. uom = obj_selection[0].units.lower()
  6532. # Define a boundary around SVG of about 1.0mm (~39mils)
  6533. if uom in "mm":
  6534. boundary = 1.0
  6535. else:
  6536. boundary = 0.0393701
  6537. # Convert everything to strings for use in the xml doc
  6538. svgwidth = str(size[0] + (2 * boundary))
  6539. svgheight = str(size[1] + (2 * boundary))
  6540. minx = str(bounds[0] - boundary)
  6541. miny = str(bounds[1] + boundary + size[1])
  6542. # Add a SVG Header and footer to the svg output from shapely
  6543. # The transform flips the Y Axis so that everything renders
  6544. # properly within svg apps such as inkscape
  6545. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6546. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6547. svg_header += 'width="' + svgwidth + uom + '" '
  6548. svg_header += 'height="' + svgheight + uom + '" '
  6549. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6550. svg_header += '>'
  6551. svg_header += '<g transform="scale(1,-1)">'
  6552. svg_footer = '</g> </svg>'
  6553. svg_elem = str(svg_header)
  6554. for svg_item in exported_svg:
  6555. svg_elem += str(svg_item)
  6556. svg_elem += str(svg_footer)
  6557. # Parse the xml through a xml parser just to add line feeds
  6558. # and to make it look more pretty for the output
  6559. doc = parse_xml_string(svg_elem)
  6560. doc_final = doc.toprettyxml()
  6561. try:
  6562. if self.defaults['units'].upper() == 'IN':
  6563. unit = inch
  6564. else:
  6565. unit = mm
  6566. doc_final = StringIO(doc_final)
  6567. drawing = svg2rlg(doc_final)
  6568. if p_size == 'Bounds':
  6569. renderPDF.drawToFile(drawing, file_name)
  6570. else:
  6571. if orientation == 'p':
  6572. page_size = portrait(self.pagesize[p_size])
  6573. else:
  6574. page_size = landscape(self.pagesize[p_size])
  6575. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6576. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6577. renderPDF.draw(drawing, my_canvas, 0, 0)
  6578. my_canvas.save()
  6579. except Exception as e:
  6580. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6581. return 'fail'
  6582. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6583. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6584. """
  6585. Exports a Geometry Object to an SVG file.
  6586. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6587. :param filename: Path to the SVG file to save to.
  6588. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6589. :return:
  6590. """
  6591. self.defaults.report_usage("export_svg()")
  6592. if filename is None:
  6593. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6594. is not None else self.defaults["global_last_folder"]
  6595. self.log.debug("export_svg()")
  6596. try:
  6597. obj = self.collection.get_by_name(str(obj_name))
  6598. except Exception:
  6599. # TODO: The return behavior has not been established... should raise exception?
  6600. return "Could not retrieve object: %s" % obj_name
  6601. with self.proc_container.new(_("Exporting SVG")) as proc:
  6602. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6603. # Determine bounding area for svg export
  6604. bounds = obj.bounds()
  6605. size = obj.size()
  6606. # Convert everything to strings for use in the xml doc
  6607. svgwidth = str(size[0])
  6608. svgheight = str(size[1])
  6609. minx = str(bounds[0])
  6610. miny = str(bounds[1] - size[1])
  6611. uom = obj.units.lower()
  6612. # Add a SVG Header and footer to the svg output from shapely
  6613. # The transform flips the Y Axis so that everything renders
  6614. # properly within svg apps such as inkscape
  6615. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6616. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6617. svg_header += 'width="' + svgwidth + uom + '" '
  6618. svg_header += 'height="' + svgheight + uom + '" '
  6619. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6620. svg_header += '<g transform="scale(1,-1)">'
  6621. svg_footer = '</g> </svg>'
  6622. svg_elem = svg_header + exported_svg + svg_footer
  6623. # Parse the xml through a xml parser just to add line feeds
  6624. # and to make it look more pretty for the output
  6625. svgcode = parse_xml_string(svg_elem)
  6626. svgcode = svgcode.toprettyxml()
  6627. try:
  6628. with open(filename, 'w') as fp:
  6629. fp.write(svgcode)
  6630. except PermissionError:
  6631. self.inform.emit('[WARNING] %s' %
  6632. _("Permission denied, saving not possible.\n"
  6633. "Most likely another app is holding the file open and not accessible."))
  6634. return 'fail'
  6635. if self.defaults["global_open_style"] is False:
  6636. self.file_opened.emit("SVG", filename)
  6637. self.file_saved.emit("SVG", filename)
  6638. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6639. def save_source_file(self, obj_name, filename, use_thread=True):
  6640. """
  6641. Exports a FlatCAM Object to an Gerber/Excellon file.
  6642. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6643. :param filename: Path to the Gerber file to save to.
  6644. :param use_thread: if to be run in a separate thread
  6645. :return:
  6646. """
  6647. self.defaults.report_usage("save source file()")
  6648. if filename is None:
  6649. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6650. is not None else self.defaults["global_last_folder"]
  6651. self.log.debug("save source file()")
  6652. obj = self.collection.get_by_name(obj_name)
  6653. file_string = StringIO(obj.source_file)
  6654. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6655. if file_string.getvalue() == '':
  6656. self.inform.emit('[ERROR_NOTCL] %s' %
  6657. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6658. return 'fail'
  6659. try:
  6660. with open(filename, 'w') as file:
  6661. file.writelines('G04*\n')
  6662. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6663. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6664. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6665. file.writelines('G04 Created on : %s*\n' % time_string)
  6666. for line in file_string:
  6667. file.writelines(line)
  6668. except PermissionError:
  6669. self.inform.emit('[WARNING] %s' %
  6670. _("Permission denied, saving not possible.\n"
  6671. "Most likely another app is holding the file open and not accessible."))
  6672. return 'fail'
  6673. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6674. """
  6675. Exports a Excellon Object to an Excellon file.
  6676. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6677. :param filename: Path to the Excellon file to save to.
  6678. :param local_use:
  6679. :param use_thread: if to be run in a separate thread
  6680. :return:
  6681. """
  6682. self.defaults.report_usage("export_excellon()")
  6683. if filename is None:
  6684. if self.defaults["global_last_save_folder"]:
  6685. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6686. else:
  6687. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6688. self.log.debug("export_excellon()")
  6689. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6690. self.defaults["excellon_exp_decimals"]
  6691. )
  6692. if local_use is None:
  6693. try:
  6694. obj = self.collection.get_by_name(str(obj_name))
  6695. except Exception:
  6696. return "Could not retrieve object: %s" % obj_name
  6697. else:
  6698. obj = local_use
  6699. if not isinstance(obj, ExcellonObject):
  6700. self.inform.emit('[ERROR_NOTCL] %s' %
  6701. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6702. return
  6703. # updated units
  6704. eunits = self.defaults["excellon_exp_units"]
  6705. ewhole = self.defaults["excellon_exp_integer"]
  6706. efract = self.defaults["excellon_exp_decimals"]
  6707. ezeros = self.defaults["excellon_exp_zeros"]
  6708. eformat = self.defaults["excellon_exp_format"]
  6709. slot_type = self.defaults["excellon_exp_slot_type"]
  6710. fc_units = self.defaults['units'].upper()
  6711. if fc_units == 'MM':
  6712. factor = 1 if eunits == 'METRIC' else 0.03937
  6713. else:
  6714. factor = 25.4 if eunits == 'METRIC' else 1
  6715. def make_excellon():
  6716. try:
  6717. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6718. header = 'M48\n'
  6719. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6720. (str(self.version), str(self.version_date))
  6721. header += ';Filename: %s' % str(obj_name) + '\n'
  6722. header += ';Created on : %s' % time_str + '\n'
  6723. if eformat == 'dec':
  6724. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6725. header += eunits + '\n'
  6726. for tool in obj.tools:
  6727. if eunits == 'METRIC':
  6728. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6729. tool=str(tool),
  6730. dec=2)
  6731. else:
  6732. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6733. tool=str(tool),
  6734. dec=4)
  6735. else:
  6736. if ezeros == 'LZ':
  6737. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6738. form='ndec', e_zeros='LZ', factor=factor,
  6739. slot_type=slot_type)
  6740. header += '%s,%s\n' % (eunits, 'LZ')
  6741. header += format_exc
  6742. for tool in obj.tools:
  6743. if eunits == 'METRIC':
  6744. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6745. tool=str(tool),
  6746. dec=2)
  6747. else:
  6748. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6749. tool=str(tool),
  6750. dec=4)
  6751. else:
  6752. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6753. form='ndec', e_zeros='TZ', factor=factor,
  6754. slot_type=slot_type)
  6755. header += '%s,%s\n' % (eunits, 'TZ')
  6756. header += format_exc
  6757. for tool in obj.tools:
  6758. if eunits == 'METRIC':
  6759. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6760. tool=str(tool),
  6761. dec=2)
  6762. else:
  6763. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6764. tool=str(tool),
  6765. dec=4)
  6766. header += '%\n'
  6767. footer = 'M30\n'
  6768. exported_excellon = header
  6769. exported_excellon += excellon_code
  6770. exported_excellon += footer
  6771. if local_use is None:
  6772. try:
  6773. with open(filename, 'w') as fp:
  6774. fp.write(exported_excellon)
  6775. except PermissionError:
  6776. self.inform.emit('[WARNING] %s' %
  6777. _("Permission denied, saving not possible.\n"
  6778. "Most likely another app is holding the file open and not accessible."))
  6779. return 'fail'
  6780. if self.defaults["global_open_style"] is False:
  6781. self.file_opened.emit("Excellon", filename)
  6782. self.file_saved.emit("Excellon", filename)
  6783. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6784. else:
  6785. return exported_excellon
  6786. except Exception as e:
  6787. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6788. return 'fail'
  6789. if use_thread is True:
  6790. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6791. def job_thread_exc(app_obj):
  6792. ret = make_excellon()
  6793. if ret == 'fail':
  6794. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6795. return
  6796. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6797. else:
  6798. eret = make_excellon()
  6799. if eret == 'fail':
  6800. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6801. return 'fail'
  6802. if local_use is not None:
  6803. return eret
  6804. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6805. """
  6806. Exports a Gerber Object to an Gerber file.
  6807. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6808. :param filename: Path to the Gerber file to save to.
  6809. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6810. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6811. :param use_thread: if to be run in a separate thread
  6812. :return:
  6813. """
  6814. self.defaults.report_usage("export_gerber()")
  6815. if filename is None:
  6816. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6817. is not None else self.defaults["global_last_folder"]
  6818. self.log.debug("export_gerber()")
  6819. if local_use is None:
  6820. try:
  6821. obj = self.collection.get_by_name(str(obj_name))
  6822. except Exception:
  6823. return "Could not retrieve object: %s" % obj_name
  6824. else:
  6825. obj = local_use
  6826. # updated units
  6827. gunits = self.defaults["gerber_exp_units"]
  6828. gwhole = self.defaults["gerber_exp_integer"]
  6829. gfract = self.defaults["gerber_exp_decimals"]
  6830. gzeros = self.defaults["gerber_exp_zeros"]
  6831. fc_units = self.defaults['units'].upper()
  6832. if fc_units == 'MM':
  6833. factor = 1 if gunits == 'MM' else 0.03937
  6834. else:
  6835. factor = 25.4 if gunits == 'MM' else 1
  6836. def make_gerber():
  6837. try:
  6838. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6839. header = 'G04*\n'
  6840. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6841. (str(self.version), str(self.version_date))
  6842. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6843. header += 'G04 Created on : %s*' % time_str + '\n'
  6844. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6845. header += "%MO{units}*%\n".format(units=gunits)
  6846. for apid in obj.apertures:
  6847. if obj.apertures[apid]['type'] == 'C':
  6848. header += "%ADD{apid}{type},{size}*%\n".format(
  6849. apid=str(apid),
  6850. type='C',
  6851. size=(factor * obj.apertures[apid]['size'])
  6852. )
  6853. elif obj.apertures[apid]['type'] == 'R':
  6854. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6855. apid=str(apid),
  6856. type='R',
  6857. width=(factor * obj.apertures[apid]['width']),
  6858. height=(factor * obj.apertures[apid]['height'])
  6859. )
  6860. elif obj.apertures[apid]['type'] == 'O':
  6861. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6862. apid=str(apid),
  6863. type='O',
  6864. width=(factor * obj.apertures[apid]['width']),
  6865. height=(factor * obj.apertures[apid]['height'])
  6866. )
  6867. header += '\n'
  6868. # obsolete units but some software may need it
  6869. if gunits == 'IN':
  6870. header += 'G70*\n'
  6871. else:
  6872. header += 'G71*\n'
  6873. # Absolute Mode
  6874. header += 'G90*\n'
  6875. header += 'G01*\n'
  6876. # positive polarity
  6877. header += '%LPD*%\n'
  6878. footer = 'M02*\n'
  6879. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6880. exported_gerber = header
  6881. exported_gerber += gerber_code
  6882. exported_gerber += footer
  6883. if local_use is None:
  6884. try:
  6885. with open(filename, 'w') as fp:
  6886. fp.write(exported_gerber)
  6887. except PermissionError:
  6888. self.inform.emit('[WARNING] %s' %
  6889. _("Permission denied, saving not possible.\n"
  6890. "Most likely another app is holding the file open and not accessible."))
  6891. return 'fail'
  6892. if self.defaults["global_open_style"] is False:
  6893. self.file_opened.emit("Gerber", filename)
  6894. self.file_saved.emit("Gerber", filename)
  6895. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6896. else:
  6897. return exported_gerber
  6898. except Exception as e:
  6899. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6900. return 'fail'
  6901. if use_thread is True:
  6902. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6903. def job_thread_grb(app_obj):
  6904. ret = make_gerber()
  6905. if ret == 'fail':
  6906. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6907. return
  6908. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6909. else:
  6910. gret = make_gerber()
  6911. if gret == 'fail':
  6912. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6913. return 'fail'
  6914. if local_use is not None:
  6915. return gret
  6916. def export_dxf(self, obj_name, filename, use_thread=True):
  6917. """
  6918. Exports a Geometry Object to an DXF file.
  6919. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6920. :param filename: Path to the DXF file to save to.
  6921. :param use_thread: if to be run in a separate thread
  6922. :return:
  6923. """
  6924. self.defaults.report_usage("export_dxf()")
  6925. if filename is None:
  6926. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6927. is not None else self.defaults["global_last_folder"]
  6928. self.log.debug("export_dxf()")
  6929. try:
  6930. obj = self.collection.get_by_name(str(obj_name))
  6931. except Exception:
  6932. # TODO: The return behavior has not been established... should raise exception?
  6933. return "Could not retrieve object: %s" % obj_name
  6934. def make_dxf():
  6935. try:
  6936. dxf_code = obj.export_dxf()
  6937. dxf_code.saveas(filename)
  6938. if self.defaults["global_open_style"] is False:
  6939. self.file_opened.emit("DXF", filename)
  6940. self.file_saved.emit("DXF", filename)
  6941. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6942. except Exception:
  6943. return 'fail'
  6944. if use_thread is True:
  6945. with self.proc_container.new(_("Exporting DXF")) as proc:
  6946. def job_thread_exc(app_obj):
  6947. ret_dxf_val = make_dxf()
  6948. if ret_dxf_val == 'fail':
  6949. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6950. return
  6951. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6952. else:
  6953. ret = make_dxf()
  6954. if ret == 'fail':
  6955. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6956. return
  6957. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6958. """
  6959. Adds a new Geometry Object to the projects and populates
  6960. it with shapes extracted from the SVG file.
  6961. :param plot: If True then the resulting object will be plotted on canvas
  6962. :param filename: Path to the SVG file.
  6963. :param geo_type: Type of FlatCAM object that will be created from SVG
  6964. :param outname: The name given to the resulting FlatCAM object
  6965. :return:
  6966. """
  6967. self.defaults.report_usage("import_svg()")
  6968. log.debug("App.import_svg()")
  6969. obj_type = ""
  6970. if geo_type is None or geo_type == "geometry":
  6971. obj_type = "geometry"
  6972. elif geo_type == "gerber":
  6973. obj_type = "gerber"
  6974. else:
  6975. self.inform.emit('[ERROR_NOTCL] %s' %
  6976. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6977. return
  6978. units = self.defaults['units'].upper()
  6979. def obj_init(geo_obj, app_obj):
  6980. geo_obj.import_svg(filename, obj_type, units=units)
  6981. geo_obj.multigeo = False
  6982. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6983. with self.proc_container.new(_("Importing SVG")) as proc:
  6984. # Object name
  6985. name = outname or filename.split('/')[-1].split('\\')[-1]
  6986. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6987. if ret == 'fail':
  6988. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6989. return 'fail'
  6990. # Register recent file
  6991. self.file_opened.emit("svg", filename)
  6992. # appGUI feedback
  6993. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6994. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6995. """
  6996. Adds a new Geometry Object to the projects and populates
  6997. it with shapes extracted from the DXF file.
  6998. :param filename: Path to the DXF file.
  6999. :param geo_type: Type of FlatCAM object that will be created from DXF
  7000. :param outname: Name for the imported Geometry
  7001. :param plot: If True then the resulting object will be plotted on canvas
  7002. :return:
  7003. """
  7004. self.defaults.report_usage("import_dxf()")
  7005. obj_type = ""
  7006. if geo_type is None or geo_type == "geometry":
  7007. obj_type = "geometry"
  7008. elif geo_type == "gerber":
  7009. obj_type = geo_type
  7010. else:
  7011. self.inform.emit('[ERROR_NOTCL] %s' %
  7012. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7013. return
  7014. units = self.defaults['units'].upper()
  7015. def obj_init(geo_obj, app_obj):
  7016. geo_obj.import_dxf(filename, obj_type, units=units)
  7017. geo_obj.multigeo = False
  7018. with self.proc_container.new(_("Importing DXF")):
  7019. # Object name
  7020. name = outname or filename.split('/')[-1].split('\\')[-1]
  7021. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7022. if ret == 'fail':
  7023. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7024. return 'fail'
  7025. # Register recent file
  7026. self.file_opened.emit("dxf", filename)
  7027. # appGUI feedback
  7028. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7029. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7030. """
  7031. Opens a Gerber file, parses it and creates a new object for
  7032. it in the program. Thread-safe.
  7033. :param outname: Name of the resulting object. None causes the
  7034. name to be that of the file. Str.
  7035. :param filename: Gerber file filename
  7036. :type filename: str
  7037. :param plot: boolean, to plot or not the resulting object
  7038. :param from_tcl: True if run from Tcl Shell
  7039. :return: None
  7040. """
  7041. # How the object should be initialized
  7042. def obj_init(gerber_obj, app_obj):
  7043. assert isinstance(gerber_obj, GerberObject), \
  7044. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7045. # Opening the file happens here
  7046. try:
  7047. gerber_obj.parse_file(filename)
  7048. except IOError:
  7049. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7050. return "fail"
  7051. except ParseError as err:
  7052. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7053. app_obj.log.error(str(err))
  7054. return "fail"
  7055. except Exception as e:
  7056. log.debug("App.open_gerber() --> %s" % str(e))
  7057. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7058. msg += traceback.format_exc()
  7059. app_obj.inform.emit(msg)
  7060. return "fail"
  7061. if gerber_obj.is_empty():
  7062. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7063. _("Object is not Gerber file or empty. Aborting object creation."))
  7064. return "fail"
  7065. App.log.debug("open_gerber()")
  7066. with self.proc_container.new(_("Opening Gerber")):
  7067. # Object name
  7068. name = outname or filename.split('/')[-1].split('\\')[-1]
  7069. # # ## Object creation # ##
  7070. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7071. if ret_val == 'fail':
  7072. if from_tcl:
  7073. filename = self.defaults['global_tcl_path'] + '/' + name
  7074. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7075. if ret_val == 'fail':
  7076. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7077. return 'fail'
  7078. # Register recent file
  7079. self.file_opened.emit("gerber", filename)
  7080. # appGUI feedback
  7081. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7082. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7083. """
  7084. Opens an Excellon file, parses it and creates a new object for
  7085. it in the program. Thread-safe.
  7086. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7087. :param filename: Excellon file filename
  7088. :type filename: str
  7089. :param plot: boolean, to plot or not the resulting object
  7090. :param from_tcl: True if run from Tcl Shell
  7091. :return: None
  7092. """
  7093. App.log.debug("open_excellon()")
  7094. # How the object should be initialized
  7095. def obj_init(excellon_obj, app_obj):
  7096. try:
  7097. ret = excellon_obj.parse_file(filename=filename)
  7098. if ret == "fail":
  7099. log.debug("Excellon parsing failed.")
  7100. self.inform.emit('[ERROR_NOTCL] %s' %
  7101. _("This is not Excellon file."))
  7102. return "fail"
  7103. except IOError:
  7104. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7105. (_("Cannot open file"), filename))
  7106. log.debug("Could not open Excellon object.")
  7107. return "fail"
  7108. except Exception:
  7109. msg = '[ERROR_NOTCL] %s' % \
  7110. _("An internal error has occurred. See shell.\n")
  7111. msg += traceback.format_exc()
  7112. app_obj.inform.emit(msg)
  7113. return "fail"
  7114. ret = excellon_obj.create_geometry()
  7115. if ret == 'fail':
  7116. log.debug("Could not create geometry for Excellon object.")
  7117. return "fail"
  7118. for tool in excellon_obj.tools:
  7119. if excellon_obj.tools[tool]['solid_geometry']:
  7120. return
  7121. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7122. return "fail"
  7123. with self.proc_container.new(_("Opening Excellon.")):
  7124. # Object name
  7125. name = outname or filename.split('/')[-1].split('\\')[-1]
  7126. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7127. if ret_val == 'fail':
  7128. if from_tcl:
  7129. filename = self.defaults['global_tcl_path'] + '/' + name
  7130. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7131. if ret_val == 'fail':
  7132. self.inform.emit('[ERROR_NOTCL] %s' %
  7133. _('Open Excellon file failed. Probable not an Excellon file.'))
  7134. return
  7135. # Register recent file
  7136. self.file_opened.emit("excellon", filename)
  7137. # appGUI feedback
  7138. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7139. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7140. """
  7141. Opens a G-gcode file, parses it and creates a new object for
  7142. it in the program. Thread-safe.
  7143. :param filename: G-code file filename
  7144. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7145. :param force_parsing:
  7146. :param plot: If True plot the object on canvas
  7147. :param from_tcl: True if run from Tcl Shell
  7148. :return: None
  7149. """
  7150. App.log.debug("open_gcode()")
  7151. # How the object should be initialized
  7152. def obj_init(job_obj, app_obj_):
  7153. """
  7154. :param job_obj: the resulting object
  7155. :type app_obj_: App
  7156. """
  7157. assert isinstance(app_obj_, App), \
  7158. "Initializer expected App, got %s" % type(app_obj_)
  7159. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7160. try:
  7161. f = open(filename)
  7162. gcode = f.read()
  7163. f.close()
  7164. except IOError:
  7165. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7166. return "fail"
  7167. job_obj.gcode = gcode
  7168. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7169. if gcode_ret == "fail":
  7170. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7171. return "fail"
  7172. job_obj.create_geometry()
  7173. with self.proc_container.new(_("Opening G-Code.")):
  7174. # Object name
  7175. name = outname or filename.split('/')[-1].split('\\')[-1]
  7176. # New object creation and file processing
  7177. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7178. if ret_val == 'fail':
  7179. if from_tcl:
  7180. filename = self.defaults['global_tcl_path'] + '/' + name
  7181. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7182. if ret_val == 'fail':
  7183. self.inform.emit('[ERROR_NOTCL] %s' %
  7184. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7185. "Try to load it from File menu.\n "
  7186. "Attempting to create a FlatCAM CNCJob Object from "
  7187. "G-Code file failed during processing"))
  7188. return "fail"
  7189. # Register recent file
  7190. self.file_opened.emit("cncjob", filename)
  7191. # appGUI feedback
  7192. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7193. def open_hpgl2(self, filename, outname=None):
  7194. """
  7195. Opens a HPGL2 file, parses it and creates a new object for
  7196. it in the program. Thread-safe.
  7197. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7198. :param filename: HPGL2 file filename
  7199. :return: None
  7200. """
  7201. filename = filename
  7202. # How the object should be initialized
  7203. def obj_init(geo_obj, app_obj):
  7204. assert isinstance(geo_obj, GeometryObject), \
  7205. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7206. # Opening the file happens here
  7207. obj = HPGL2(self)
  7208. try:
  7209. HPGL2.parse_file(obj, filename)
  7210. except IOError:
  7211. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7212. return "fail"
  7213. except ParseError as err:
  7214. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7215. app_obj.log.error(str(err))
  7216. return "fail"
  7217. except Exception as e:
  7218. log.debug("App.open_hpgl2() --> %s" % str(e))
  7219. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7220. msg += traceback.format_exc()
  7221. app_obj.inform.emit(msg)
  7222. return "fail"
  7223. geo_obj.multigeo = True
  7224. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7225. geo_obj.tools = deepcopy(obj.tools)
  7226. geo_obj.source_file = deepcopy(obj.source_file)
  7227. del obj
  7228. if not geo_obj.solid_geometry:
  7229. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7230. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7231. return "fail"
  7232. App.log.debug("open_hpgl2()")
  7233. with self.proc_container.new(_("Opening HPGL2")):
  7234. # Object name
  7235. name = outname or filename.split('/')[-1].split('\\')[-1]
  7236. # # ## Object creation # ##
  7237. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7238. if ret == 'fail':
  7239. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7240. return 'fail'
  7241. # Register recent file
  7242. self.file_opened.emit("geometry", filename)
  7243. # appGUI feedback
  7244. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7245. def open_script(self, filename, outname=None, silent=False):
  7246. """
  7247. Opens a Script file, parses it and creates a new object for
  7248. it in the program. Thread-safe.
  7249. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7250. :param filename: Script file filename
  7251. :param silent: If True there will be no messages printed to StatusBar
  7252. :return: None
  7253. """
  7254. def obj_init(script_obj, app_obj):
  7255. assert isinstance(script_obj, ScriptObject), \
  7256. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7257. if silent is False:
  7258. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7259. try:
  7260. script_obj.parse_file(filename)
  7261. except IOError:
  7262. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7263. return "fail"
  7264. except ParseError as err:
  7265. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7266. app_obj.log.error(str(err))
  7267. return "fail"
  7268. except Exception as e:
  7269. log.debug("App.open_script() -> %s" % str(e))
  7270. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7271. msg += traceback.format_exc()
  7272. app_obj.inform.emit(msg)
  7273. return "fail"
  7274. App.log.debug("open_script()")
  7275. with self.proc_container.new(_("Opening TCL Script...")):
  7276. # Object name
  7277. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7278. # Object creation
  7279. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7280. if ret_val == 'fail':
  7281. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7282. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7283. if ret_val == 'fail':
  7284. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7285. return 'fail'
  7286. # Register recent file
  7287. self.file_opened.emit("script", filename)
  7288. # appGUI feedback
  7289. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7290. def open_config_file(self, filename, run_from_arg=None):
  7291. """
  7292. Loads a config file from the specified file.
  7293. :param filename: Name of the file from which to load.
  7294. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7295. :return: None
  7296. """
  7297. App.log.debug("Opening config file: " + filename)
  7298. if run_from_arg:
  7299. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7300. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7301. _("Opening FlatCAM Config file.")),
  7302. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7303. color=QtGui.QColor("gray"))
  7304. # # add the tab if it was closed
  7305. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7306. # # first clear previous text in text editor (if any)
  7307. # self.ui.text_editor_tab.code_editor.clear()
  7308. #
  7309. # # Switch plot_area to CNCJob tab
  7310. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7311. # close the Code editor if already open
  7312. if self.toggle_codeeditor:
  7313. self.on_toggle_code_editor()
  7314. self.on_toggle_code_editor()
  7315. try:
  7316. if filename:
  7317. f = QtCore.QFile(filename)
  7318. if f.open(QtCore.QIODevice.ReadOnly):
  7319. stream = QtCore.QTextStream(f)
  7320. code_edited = stream.readAll()
  7321. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7322. f.close()
  7323. except IOError:
  7324. App.log.error("Failed to open config file: %s" % filename)
  7325. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7326. (_("Failed to open config file"), filename))
  7327. return
  7328. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7329. """
  7330. Loads a project from the specified file.
  7331. 1) Loads and parses file
  7332. 2) Registers the file as recently opened.
  7333. 3) Calls on_file_new()
  7334. 4) Updates options
  7335. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7336. 6) Calls plot_all() if plot=True
  7337. :param filename: Name of the file from which to load.
  7338. :param run_from_arg: True if run for arguments
  7339. :param plot: If True plot all objects in the project
  7340. :param cli: Run from command line
  7341. :param from_tcl: True if run from Tcl Sehll
  7342. :return: None
  7343. """
  7344. App.log.debug("Opening project: " + filename)
  7345. # block autosaving while a project is loaded
  7346. self.block_autosave = True
  7347. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7348. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7349. if cli is None:
  7350. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7351. if run_from_arg:
  7352. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7353. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7354. _("Opening FlatCAM Project file.")),
  7355. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7356. color=QtGui.QColor("gray"))
  7357. # Open and parse an uncompressed Project file
  7358. try:
  7359. f = open(filename, 'r')
  7360. except IOError:
  7361. if from_tcl:
  7362. name = filename.split('/')[-1].split('\\')[-1]
  7363. filename = self.defaults['global_tcl_path'] + '/' + name
  7364. try:
  7365. f = open(filename, 'r')
  7366. except IOError:
  7367. log.error("Failed to open project file: %s" % filename)
  7368. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7369. return
  7370. else:
  7371. log.error("Failed to open project file: %s" % filename)
  7372. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7373. return
  7374. try:
  7375. d = json.load(f, object_hook=dict2obj)
  7376. except Exception as e:
  7377. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7378. (filename, str(e)))
  7379. f.close()
  7380. # Open and parse a compressed Project file
  7381. try:
  7382. with lzma.open(filename) as f:
  7383. file_content = f.read().decode('utf-8')
  7384. d = json.loads(file_content, object_hook=dict2obj)
  7385. except Exception as e:
  7386. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7387. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7388. return
  7389. # Clear the current project
  7390. # # NOT THREAD SAFE # ##
  7391. if run_from_arg is True:
  7392. pass
  7393. elif cli is True:
  7394. self.delete_selection_shape()
  7395. else:
  7396. self.on_file_new()
  7397. # Project options
  7398. self.options.update(d['options'])
  7399. self.project_filename = filename
  7400. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7401. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7402. if cli is None:
  7403. self.set_screen_units(self.options["units"])
  7404. # Re create objects
  7405. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7406. for obj in d['objs']:
  7407. try:
  7408. def obj_init(obj_inst, app_inst):
  7409. obj_inst.from_dict(obj)
  7410. App.log.debug("Recreating from opened project an %s object: %s" %
  7411. (obj['kind'].capitalize(), obj['options']['name']))
  7412. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7413. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7414. if cli is None:
  7415. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7416. obj['kind'].upper(),
  7417. obj['options']['name']
  7418. )
  7419. )
  7420. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7421. except Exception as e:
  7422. print('App.open_project() --> ' + str(e))
  7423. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7424. self.should_we_save = False
  7425. self.file_opened.emit("project", filename)
  7426. # restore autosaving after a project was loaded
  7427. self.block_autosave = False
  7428. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7429. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7430. if cli is None:
  7431. self.set_ui_title(name=self.project_filename)
  7432. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7433. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7434. """
  7435. Re-generates all plots from all objects.
  7436. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7437. :param muted: if True don't print messages
  7438. :param use_thread: if True will use threading for plotting the objects
  7439. :return: None
  7440. """
  7441. self.log.debug("Plot_all()")
  7442. if muted is not True:
  7443. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7444. for plot_obj in self.collection.get_list():
  7445. def worker_task(obj):
  7446. with self.proc_container.new("Plotting"):
  7447. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7448. if fit_view is True:
  7449. self.app_obj.object_plotted.emit(obj)
  7450. if use_thread is True:
  7451. # Send to worker
  7452. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7453. else:
  7454. worker_task(plot_obj)
  7455. def register_folder(self, filename):
  7456. """
  7457. Register the last folder used by the app to open something
  7458. :param filename: the last folder is extracted from the filename
  7459. :return: None
  7460. """
  7461. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7462. def register_save_folder(self, filename):
  7463. """
  7464. Register the last folder used by the app to save something
  7465. :param filename: the last folder is extracted from the filename
  7466. :return: None
  7467. """
  7468. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7469. # def set_progress_bar(self, percentage, text=""):
  7470. # """
  7471. # Set a progress bar to a value (percentage)
  7472. #
  7473. # :param percentage: Value set to the progressbar
  7474. # :param text: Not used
  7475. # :return: None
  7476. # """
  7477. # self.ui.progress_bar.setValue(int(percentage))
  7478. def setup_recent_items(self):
  7479. """
  7480. Setup a dictionary with the recent files accessed, organized by type
  7481. :return:
  7482. """
  7483. icons = {
  7484. "gerber": self.resource_location + "/flatcam_icon16.png",
  7485. "excellon": self.resource_location + "/drill16.png",
  7486. 'geometry': self.resource_location + "/geometry16.png",
  7487. "cncjob": self.resource_location + "/cnc16.png",
  7488. "script": self.resource_location + "/script_new24.png",
  7489. "document": self.resource_location + "/notes16_1.png",
  7490. "project": self.resource_location + "/project16.png",
  7491. "svg": self.resource_location + "/geometry16.png",
  7492. "dxf": self.resource_location + "/dxf16.png",
  7493. "pdf": self.resource_location + "/pdf32.png",
  7494. "image": self.resource_location + "/image16.png"
  7495. }
  7496. try:
  7497. image_opener = self.image_tool.import_image
  7498. except AttributeError:
  7499. image_opener = None
  7500. openers = {
  7501. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7502. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7503. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7504. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7505. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7506. "document": None,
  7507. 'project': self.open_project,
  7508. 'svg': self.import_svg,
  7509. 'dxf': self.import_dxf,
  7510. 'image': image_opener,
  7511. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7512. }
  7513. # Open recent file for files
  7514. try:
  7515. f = open(self.data_path + '/recent.json')
  7516. except IOError:
  7517. App.log.error("Failed to load recent item list.")
  7518. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7519. return
  7520. try:
  7521. self.recent = json.load(f)
  7522. except json.errors.JSONDecodeError:
  7523. App.log.error("Failed to parse recent item list.")
  7524. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7525. f.close()
  7526. return
  7527. f.close()
  7528. # Open recent file for projects
  7529. try:
  7530. fp = open(self.data_path + '/recent_projects.json')
  7531. except IOError:
  7532. App.log.error("Failed to load recent project item list.")
  7533. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7534. return
  7535. try:
  7536. self.recent_projects = json.load(fp)
  7537. except json.errors.JSONDecodeError:
  7538. App.log.error("Failed to parse recent project item list.")
  7539. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7540. fp.close()
  7541. return
  7542. fp.close()
  7543. # Closure needed to create callbacks in a loop.
  7544. # Otherwise late binding occurs.
  7545. def make_callback(func, fname):
  7546. def opener():
  7547. func(fname)
  7548. return opener
  7549. def reset_recent_files():
  7550. # Reset menu
  7551. self.ui.recent.clear()
  7552. self.recent = []
  7553. try:
  7554. ff = open(self.data_path + '/recent.json', 'w')
  7555. except IOError:
  7556. App.log.error("Failed to open recent items file for writing.")
  7557. return
  7558. json.dump(self.recent, ff)
  7559. def reset_recent_projects():
  7560. # Reset menu
  7561. self.ui.recent_projects.clear()
  7562. self.recent_projects = []
  7563. try:
  7564. frp = open(self.data_path + '/recent_projects.json', 'w')
  7565. except IOError:
  7566. App.log.error("Failed to open recent projects items file for writing.")
  7567. return
  7568. json.dump(self.recent, frp)
  7569. # Reset menu
  7570. self.ui.recent.clear()
  7571. self.ui.recent_projects.clear()
  7572. # Create menu items for projects
  7573. for recent in self.recent_projects:
  7574. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7575. if recent['kind'] == 'project':
  7576. try:
  7577. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7578. # Attach callback
  7579. o = make_callback(openers[recent["kind"]], recent['filename'])
  7580. action.triggered.connect(o)
  7581. self.ui.recent_projects.addAction(action)
  7582. except KeyError:
  7583. App.log.error("Unsupported file type: %s" % recent["kind"])
  7584. # Last action in Recent Files menu is one that Clear the content
  7585. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7586. (_("Clear Recent projects")), self)
  7587. clear_action_proj.triggered.connect(reset_recent_projects)
  7588. self.ui.recent_projects.addSeparator()
  7589. self.ui.recent_projects.addAction(clear_action_proj)
  7590. # Create menu items for files
  7591. for recent in self.recent:
  7592. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7593. if recent['kind'] != 'project':
  7594. try:
  7595. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7596. # Attach callback
  7597. o = make_callback(openers[recent["kind"]], recent['filename'])
  7598. action.triggered.connect(o)
  7599. self.ui.recent.addAction(action)
  7600. except KeyError:
  7601. App.log.error("Unsupported file type: %s" % recent["kind"])
  7602. # Last action in Recent Files menu is one that Clear the content
  7603. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7604. (_("Clear Recent files")), self)
  7605. clear_action.triggered.connect(reset_recent_files)
  7606. self.ui.recent.addSeparator()
  7607. self.ui.recent.addAction(clear_action)
  7608. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7609. # self.ui.menufilerecent.set_submenu(recent_menu)
  7610. # recent_menu.show_all()
  7611. # self.ui.recent.show()
  7612. self.log.debug("Recent items list has been populated.")
  7613. def setup_component_editor(self):
  7614. """
  7615. Default text for the Selected tab when is not taken by the Object UI.
  7616. :return:
  7617. """
  7618. # label = QtWidgets.QLabel("Choose an item from Project")
  7619. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7620. sel_title = QtWidgets.QTextEdit(
  7621. _('<b>Shortcut Key List</b>'))
  7622. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7623. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7624. f_settings = QSettings("Open Source", "FlatCAM")
  7625. if f_settings.contains("notebook_font_size"):
  7626. fsize = f_settings.value('notebook_font_size', type=int)
  7627. else:
  7628. fsize = 12
  7629. tsize = fsize + int(fsize / 2)
  7630. # selected_text = (_('''
  7631. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7632. # </p>
  7633. #
  7634. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7635. # The normal flow when working in FlatCAM is the following:</span></p>
  7636. #
  7637. # <ol>
  7638. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7639. # file into
  7640. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7641. # even dragging and dropping the files on the appGUI.<br />
  7642. # <br />
  7643. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7644. # drop of the
  7645. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7646. # &nbsp;</li>
  7647. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7648. # and then
  7649. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7650. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7651. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7652. # <br />
  7653. # If the selection of the object is done on the canvas by single click instead, and the
  7654. # <strong>SELECTED TAB</strong>
  7655. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7656. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7657. # it even if it was out of focus.<br />
  7658. # <br />
  7659. # You can change the parameters in this screen and the flow direction is like this:<br />
  7660. # <br />
  7661. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7662. # <strong> Geometry Object
  7663. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7664. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7665. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7666. # </ol>
  7667. #
  7668. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7669. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7670. # <strong>F3</strong>.</span></p>
  7671. #
  7672. # ''').format(fsize=fsize, tsize=tsize))
  7673. selected_text = '''
  7674. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7675. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7676. {s1}</span></p>
  7677. <ol>
  7678. <li><span style="font-size:{fsize}px">{s2}<br />
  7679. <br />
  7680. {s3}</span><br />
  7681. &nbsp;</li>
  7682. <li><span style="font-size:{fsize}px">{s4}<br />
  7683. &nbsp;</li>
  7684. <br />
  7685. <li><span style="font-size:{fsize}px">{s5}<br />
  7686. &nbsp;</li>
  7687. <br />
  7688. <li><span style="font-size:{fsize}px">{s6}<br />
  7689. <br />
  7690. {s7}</span></li>
  7691. </ol>
  7692. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7693. '''.format(
  7694. title=_("Selected Tab - Choose an Item from Project Tab"),
  7695. subtitle=_("Details"),
  7696. s1=_("The normal flow when working with the application is the following:"),
  7697. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7698. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7699. "files on the GUI."),
  7700. s3=_("You can also load a project by double clicking on the project file, "
  7701. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7702. "actions offered within the app."),
  7703. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7704. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7705. "SELECTED TAB will be updated with the object properties according to its kind: "
  7706. "Gerber, Excellon, Geometry or CNCJob object."),
  7707. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7708. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7709. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7710. "the SELECTED TAB and populate it even if it was out of focus."),
  7711. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7712. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7713. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7714. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7715. "(again, done in SELECTED TAB) --> Save GCode."),
  7716. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7717. "or through its own key shortcut: <b>F3</b>."),
  7718. tsize=tsize,
  7719. fsize=fsize
  7720. )
  7721. sel_title.setText(selected_text)
  7722. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7723. self.ui.selected_scroll_area.setWidget(sel_title)
  7724. def setup_obj_classes(self):
  7725. """
  7726. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7727. class.
  7728. :return: None
  7729. """
  7730. FlatCAMObj.app = self
  7731. ObjectCollection.app = self
  7732. Gerber.app = self
  7733. Excellon.app = self
  7734. Geometry.app = self
  7735. CNCjob.app = self
  7736. FCProcess.app = self
  7737. FCProcessContainer.app = self
  7738. OptionsGroupUI.app = self
  7739. def version_check(self):
  7740. """
  7741. Checks for the latest version of the program. Alerts the
  7742. user if theirs is outdated. This method is meant to be run
  7743. in a separate thread.
  7744. :return: None
  7745. """
  7746. self.log.debug("version_check()")
  7747. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7748. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7749. App.version_url,
  7750. str(self.defaults['global_serial']),
  7751. str(self.version),
  7752. str(self.os),
  7753. urllib.parse.urlencode(self.defaults["global_stats"])
  7754. )
  7755. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7756. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7757. # urllib.parse.urlencode(self.defaults["global_stats"])
  7758. else:
  7759. # no_stats dict; just so it won't break things on website
  7760. no_ststs_dict = {}
  7761. no_ststs_dict["global_ststs"] = {}
  7762. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7763. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7764. App.log.debug("Checking for updates @ %s" % full_url)
  7765. # ## Get the data
  7766. try:
  7767. f = urllib.request.urlopen(full_url)
  7768. except Exception:
  7769. # App.log.warning("Failed checking for latest version. Could not connect.")
  7770. self.log.warning("Failed checking for latest version. Could not connect.")
  7771. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7772. return
  7773. try:
  7774. data = json.load(f)
  7775. except Exception as e:
  7776. App.log.error("Could not parse information about latest version.")
  7777. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7778. App.log.debug("json.load(): %s" % str(e))
  7779. f.close()
  7780. return
  7781. f.close()
  7782. # ## Latest version?
  7783. if self.version >= data["version"]:
  7784. App.log.debug("FlatCAM is up to date!")
  7785. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7786. return
  7787. App.log.debug("Newer version available.")
  7788. self.message.emit(
  7789. _("Newer Version Available"),
  7790. '%s<br><br>><b>%s</b><br>%s' % (
  7791. _("There is a newer version of FlatCAM available for download:"),
  7792. str(data["name"]),
  7793. str(data["message"])
  7794. ),
  7795. _("info")
  7796. )
  7797. def on_plotcanvas_setup(self, container=None):
  7798. """
  7799. This is doing the setup for the plot area (canvas).
  7800. :param container: QT Widget where to install the canvas
  7801. :return: None
  7802. """
  7803. if container:
  7804. plot_container = container
  7805. else:
  7806. plot_container = self.ui.right_layout
  7807. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7808. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7809. self.is_legacy = True
  7810. self.defaults["global_graphic_engine"] = "2D"
  7811. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7812. else:
  7813. try:
  7814. self.plotcanvas = PlotCanvas(plot_container, self)
  7815. except Exception as er:
  7816. msg_txt = traceback.format_exc()
  7817. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7818. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7819. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7820. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7821. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7822. msg += msg_txt
  7823. self.inform.emit(msg)
  7824. return 'fail'
  7825. # So it can receive key presses
  7826. self.plotcanvas.native.setFocus()
  7827. if self.is_legacy is False:
  7828. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7829. # Set the mouse button for panning
  7830. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7831. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7832. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7833. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7834. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7835. # Keys over plot enabled
  7836. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7837. if self.defaults['global_cursor_type'] == 'small':
  7838. self.app_cursor = self.plotcanvas.new_cursor()
  7839. else:
  7840. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7841. if self.ui.grid_snap_btn.isChecked():
  7842. self.app_cursor.enabled = True
  7843. else:
  7844. self.app_cursor.enabled = False
  7845. if self.is_legacy is False:
  7846. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7847. else:
  7848. # will use the default Matplotlib axes
  7849. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7850. def on_zoom_fit(self):
  7851. """
  7852. Callback for zoom-fit request. This can be either from the corresponding
  7853. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7854. with axes limits from the geometry bounds of all objects.
  7855. :return: None
  7856. """
  7857. if self.is_legacy is False:
  7858. self.plotcanvas.fit_view()
  7859. else:
  7860. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7861. width = xmax - xmin
  7862. height = ymax - ymin
  7863. xmin -= 0.05 * width
  7864. xmax += 0.05 * width
  7865. ymin -= 0.05 * height
  7866. ymax += 0.05 * height
  7867. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7868. def on_zoom_in(self):
  7869. """
  7870. Callback for zoom-in request.
  7871. :return:
  7872. """
  7873. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7874. def on_zoom_out(self):
  7875. """
  7876. Callback for zoom-out request.
  7877. :return:
  7878. """
  7879. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7880. def disable_all_plots(self):
  7881. self.defaults.report_usage("disable_all_plots()")
  7882. self.disable_plots(self.collection.get_list())
  7883. self.inform.emit('[success] %s' %
  7884. _("All plots disabled."))
  7885. def disable_other_plots(self):
  7886. self.defaults.report_usage("disable_other_plots()")
  7887. self.disable_plots(self.collection.get_non_selected())
  7888. self.inform.emit('[success] %s' %
  7889. _("All non selected plots disabled."))
  7890. def enable_all_plots(self):
  7891. self.defaults.report_usage("enable_all_plots()")
  7892. self.enable_plots(self.collection.get_list())
  7893. self.inform.emit('[success] %s' %
  7894. _("All plots enabled."))
  7895. def on_enable_sel_plots(self):
  7896. log.debug("App.on_enable_sel_plot()")
  7897. object_list = self.collection.get_selected()
  7898. self.enable_plots(objects=object_list)
  7899. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7900. def on_disable_sel_plots(self):
  7901. log.debug("App.on_disable_sel_plot()")
  7902. # self.inform.emit(_("Disabling plots ..."))
  7903. object_list = self.collection.get_selected()
  7904. self.disable_plots(objects=object_list)
  7905. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7906. def enable_plots(self, objects):
  7907. """
  7908. Enable plots
  7909. :param objects: list of Objects to be enabled
  7910. :return:
  7911. """
  7912. log.debug("Enabling plots ...")
  7913. # self.inform.emit(_("Working ..."))
  7914. for obj in objects:
  7915. if obj.options['plot'] is False:
  7916. obj.options.set_change_callback(lambda x: None)
  7917. obj.options['plot'] = True
  7918. try:
  7919. # only the Gerber obj has on_plot_cb_click() method
  7920. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7921. # disable this cb while disconnected,
  7922. # in case the operation takes time the user is not allowed to change it
  7923. obj.ui.plot_cb.setDisabled(True)
  7924. except AttributeError:
  7925. pass
  7926. obj.set_form_item("plot")
  7927. try:
  7928. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7929. obj.ui.plot_cb.setDisabled(False)
  7930. except AttributeError:
  7931. pass
  7932. obj.options.set_change_callback(obj.on_options_change)
  7933. def worker_task(objs):
  7934. with self.proc_container.new(_("Enabling plots ...")):
  7935. for plot_obj in objs:
  7936. # obj.options['plot'] = True
  7937. if isinstance(plot_obj, CNCJobObject):
  7938. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7939. else:
  7940. plot_obj.plot(visible=True)
  7941. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7942. def disable_plots(self, objects):
  7943. """
  7944. Disables plots
  7945. :param objects: list of Objects to be disabled
  7946. :return:
  7947. """
  7948. # if no objects selected then do nothing
  7949. if not self.collection.get_selected():
  7950. return
  7951. log.debug("Disabling plots ...")
  7952. # self.inform.emit(_("Working ..."))
  7953. for obj in objects:
  7954. if obj.options['plot'] is True:
  7955. obj.options.set_change_callback(lambda x: None)
  7956. obj.options['plot'] = False
  7957. try:
  7958. # only the Gerber obj has on_plot_cb_click() method
  7959. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7960. obj.ui.plot_cb.setDisabled(True)
  7961. except AttributeError:
  7962. pass
  7963. obj.set_form_item("plot")
  7964. try:
  7965. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7966. obj.ui.plot_cb.setDisabled(False)
  7967. except AttributeError:
  7968. pass
  7969. obj.options.set_change_callback(obj.on_options_change)
  7970. try:
  7971. self.delete_selection_shape()
  7972. except Exception as e:
  7973. log.debug("App.disable_plots() --> %s" % str(e))
  7974. def worker_task(objs):
  7975. with self.proc_container.new(_("Disabling plots ...")):
  7976. for plot_obj in objs:
  7977. # obj.options['plot'] = True
  7978. if isinstance(plot_obj, CNCJobObject):
  7979. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7980. else:
  7981. plot_obj.plot(visible=False)
  7982. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7983. def toggle_plots(self, objects):
  7984. """
  7985. Toggle plots visibility
  7986. :param objects: list of Objects for which to be toggled the visibility
  7987. :return: None
  7988. """
  7989. # if no objects selected then do nothing
  7990. if not self.collection.get_selected():
  7991. return
  7992. log.debug("Toggling plots ...")
  7993. self.inform.emit(_("Working ..."))
  7994. for obj in objects:
  7995. if obj.options['plot'] is False:
  7996. obj.options['plot'] = True
  7997. else:
  7998. obj.options['plot'] = False
  7999. self.app_obj.plots_updated.emit()
  8000. def clear_plots(self):
  8001. """
  8002. Clear the plots
  8003. :return: None
  8004. """
  8005. objects = self.collection.get_list()
  8006. for obj in objects:
  8007. obj.clear(obj == objects[-1])
  8008. # Clear pool to free memory
  8009. self.clear_pool()
  8010. def on_set_color_action_triggered(self):
  8011. """
  8012. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8013. :return:
  8014. """
  8015. new_color = self.defaults['gerber_plot_fill']
  8016. clicked_action = self.sender()
  8017. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8018. act_name = clicked_action.text()
  8019. sel_obj_list = self.collection.get_selected()
  8020. if not sel_obj_list:
  8021. return
  8022. # a default value, I just chose this one
  8023. alpha_level = 'BF'
  8024. for sel_obj in sel_obj_list:
  8025. if sel_obj.kind == 'excellon':
  8026. alpha_level = str(hex(
  8027. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8028. elif sel_obj.kind == 'gerber':
  8029. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8030. elif sel_obj.kind == 'geometry':
  8031. alpha_level = 'FF'
  8032. else:
  8033. log.debug(
  8034. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8035. continue
  8036. sel_obj.alpha_level = alpha_level
  8037. if act_name == _('Red'):
  8038. new_color = '#FF0000' + alpha_level
  8039. if act_name == _('Blue'):
  8040. new_color = '#0000FF' + alpha_level
  8041. if act_name == _('Yellow'):
  8042. new_color = '#FFDF00' + alpha_level
  8043. if act_name == _('Green'):
  8044. new_color = '#00FF00' + alpha_level
  8045. if act_name == _('Purple'):
  8046. new_color = '#FF00FF' + alpha_level
  8047. if act_name == _('Brown'):
  8048. new_color = '#A52A2A' + alpha_level
  8049. if act_name == _('White'):
  8050. new_color = '#FFFFFF' + alpha_level
  8051. if act_name == _('Black'):
  8052. new_color = '#000000' + alpha_level
  8053. if act_name == _('Custom'):
  8054. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8055. c_dialog = QtWidgets.QColorDialog()
  8056. plot_fill_color = c_dialog.getColor(initial=new_color)
  8057. if plot_fill_color.isValid() is False:
  8058. return
  8059. new_color = str(plot_fill_color.name()) + alpha_level
  8060. if act_name == _("Default"):
  8061. for sel_obj in sel_obj_list:
  8062. if sel_obj.kind == 'excellon':
  8063. new_color = self.defaults['excellon_plot_fill']
  8064. new_line_color = self.defaults['excellon_plot_line']
  8065. elif sel_obj.kind == 'gerber':
  8066. new_color = self.defaults['gerber_plot_fill']
  8067. new_line_color = self.defaults['gerber_plot_line']
  8068. elif sel_obj.kind == 'geometry':
  8069. new_color = self.defaults['geometry_plot_line']
  8070. new_line_color = self.defaults['geometry_plot_line']
  8071. else:
  8072. log.debug(
  8073. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8074. continue
  8075. sel_obj.fill_color = new_color
  8076. sel_obj.outline_color = new_line_color
  8077. sel_obj.shapes.redraw(
  8078. update_colors=(new_color, new_line_color)
  8079. )
  8080. return
  8081. if act_name == _("Opacity"):
  8082. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8083. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8084. if ok_button:
  8085. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8086. for sel_obj in sel_obj_list:
  8087. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8088. sel_obj.shapes.redraw(
  8089. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8090. )
  8091. return
  8092. new_line_color = color_variant(new_color[:7], 0.7)
  8093. if act_name == _("White"):
  8094. new_line_color = color_variant("#dedede", 0.7)
  8095. for sel_obj in sel_obj_list:
  8096. sel_obj.fill_color = new_color
  8097. sel_obj.outline_color = new_line_color
  8098. sel_obj.shapes.redraw(
  8099. update_colors=(new_color, new_line_color)
  8100. )
  8101. def generate_cnc_job(self, objects):
  8102. """
  8103. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8104. :param objects: Selected objects in the Project Tab
  8105. :return:
  8106. """
  8107. self.defaults.report_usage("generate_cnc_job()")
  8108. # for obj in objects:
  8109. # obj.generatecncjob()
  8110. for obj in objects:
  8111. obj.on_generatecnc_button_click()
  8112. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8113. """
  8114. Saves the current project to the specified file.
  8115. :param filename: Name of the file in which to save.
  8116. :type filename: str
  8117. :param quit_action: if the project saving will be followed by an app quit; boolean
  8118. :param silent: if True will not display status messages
  8119. :param from_tcl True is run from Tcl Shell
  8120. :return: None
  8121. """
  8122. self.log.debug("save_project()")
  8123. self.save_in_progress = True
  8124. with self.proc_container.new(_("Saving FlatCAM Project")):
  8125. # Capture the latest changes
  8126. # Current object
  8127. try:
  8128. current_object = self.collection.get_active()
  8129. if current_object:
  8130. current_object.read_form()
  8131. except Exception as e:
  8132. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8133. pass
  8134. # Serialize the whole project
  8135. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8136. "options": self.options,
  8137. "version": self.version}
  8138. if self.defaults["global_save_compressed"] is True:
  8139. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8140. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8141. # # Write
  8142. f.write(g)
  8143. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8144. else:
  8145. # Open file
  8146. try:
  8147. f = open(filename, 'w')
  8148. except IOError:
  8149. App.log.error("Failed to open file for saving: %s", filename)
  8150. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8151. return
  8152. # Write
  8153. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8154. f.close()
  8155. # verification of the saved project
  8156. # Open and parse
  8157. try:
  8158. saved_f = open(filename, 'r')
  8159. except IOError:
  8160. if silent is False:
  8161. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8162. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8163. return
  8164. try:
  8165. saved_d = json.load(saved_f, object_hook=dict2obj)
  8166. except Exception:
  8167. if silent is False:
  8168. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8169. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8170. f.close()
  8171. return
  8172. saved_f.close()
  8173. if silent is False:
  8174. if 'version' in saved_d:
  8175. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8176. else:
  8177. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8178. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8179. tb_settings = QSettings("Open Source", "FlatCAM")
  8180. lock_state = self.ui.lock_action.isChecked()
  8181. tb_settings.setValue('toolbar_lock', lock_state)
  8182. # This will write the setting to the platform specific storage.
  8183. del tb_settings
  8184. # if quit:
  8185. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8186. # t.start()
  8187. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8188. def start_delayed_quit(self, delay, filename, should_quit=None):
  8189. """
  8190. :param delay: period of checking if project file size is more than zero; in seconds
  8191. :param filename: the name of the project file to be checked periodically for size more than zero
  8192. :param should_quit: if the task finished will be followed by an app quit; boolean
  8193. :return:
  8194. """
  8195. to_quit = should_quit
  8196. self.save_timer = QtCore.QTimer()
  8197. self.save_timer.setInterval(delay)
  8198. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8199. self.save_timer.start()
  8200. def check_project_file_size(self, filename, should_quit=None):
  8201. """
  8202. :param filename: the name of the project file to be checked periodically for size more than zero
  8203. :param should_quit: will quit the app if True; boolean
  8204. :return:
  8205. """
  8206. try:
  8207. if os.stat(filename).st_size > 0:
  8208. self.save_in_progress = False
  8209. self.save_timer.stop()
  8210. if should_quit:
  8211. self.app_quit.emit()
  8212. except Exception:
  8213. traceback.print_exc()
  8214. def save_project_auto(self):
  8215. """
  8216. Called periodically to save the project.
  8217. 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
  8218. # progress.
  8219. :return:
  8220. """
  8221. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8222. self.on_file_saveproject()
  8223. def save_project_auto_update(self):
  8224. """
  8225. Update the auto save time interval value.
  8226. :return:
  8227. """
  8228. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8229. try:
  8230. if self.autosave_timer.isActive():
  8231. self.autosave_timer.stop()
  8232. except Exception:
  8233. pass
  8234. if self.defaults['global_autosave'] is True:
  8235. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8236. self.autosave_timer.start()
  8237. def on_options_app2project(self):
  8238. """
  8239. Callback for Options->Transfer Options->App=>Project. Copies options
  8240. from application defaults to project defaults.
  8241. :return: None
  8242. """
  8243. self.defaults.report_usage("on_options_app2project")
  8244. self.preferencesUiManager.defaults_read_form()
  8245. self.options.update(self.defaults)
  8246. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8247. """
  8248. Shows a message on the FlatCAM Shell
  8249. :param msg: Message to display.
  8250. :param show: Opens the shell.
  8251. :param error: Shows the message as an error.
  8252. :param warning: Shows the message as an warning.
  8253. :param success: Shows the message as an success.
  8254. :param selected: Indicate that something was selected on canvas
  8255. :return: None
  8256. """
  8257. if show:
  8258. self.ui.shell_dock.show()
  8259. try:
  8260. if error:
  8261. self.shell.append_error(msg + "\n")
  8262. elif warning:
  8263. self.shell.append_warning(msg + "\n")
  8264. elif success:
  8265. self.shell.append_success(msg + "\n")
  8266. elif selected:
  8267. self.shell.append_selected(msg + "\n")
  8268. else:
  8269. self.shell.append_output(msg + "\n")
  8270. except AttributeError:
  8271. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8272. class ArgsThread(QtCore.QObject):
  8273. open_signal = pyqtSignal(list)
  8274. start = pyqtSignal()
  8275. stop = pyqtSignal()
  8276. if sys.platform == 'win32':
  8277. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8278. else:
  8279. address = ('/tmp/testipc', 'AF_UNIX')
  8280. def __init__(self):
  8281. super().__init__()
  8282. self.listener = None
  8283. self.thread_exit = False
  8284. self.start.connect(self.run)
  8285. self.stop.connect(self.close_listener)
  8286. def my_loop(self, address):
  8287. try:
  8288. self.listener = Listener(*address)
  8289. while self.thread_exit is False:
  8290. conn = self.listener.accept()
  8291. self.serve(conn)
  8292. except socket.error:
  8293. try:
  8294. conn = Client(*address)
  8295. conn.send(sys.argv)
  8296. conn.send('close')
  8297. # close the current instance only if there are args
  8298. if len(sys.argv) > 1:
  8299. try:
  8300. self.listener.close()
  8301. except Exception:
  8302. pass
  8303. sys.exit()
  8304. except ConnectionRefusedError:
  8305. if sys.platform == 'win32':
  8306. pass
  8307. else:
  8308. os.system('rm /tmp/testipc')
  8309. self.listener = Listener(*address)
  8310. while True:
  8311. conn = self.listener.accept()
  8312. self.serve(conn)
  8313. def serve(self, conn):
  8314. while self.thread_exit is False:
  8315. msg = conn.recv()
  8316. if msg == 'close':
  8317. break
  8318. self.open_signal.emit(msg)
  8319. conn.close()
  8320. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8321. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8322. @pyqtSlot()
  8323. def run(self):
  8324. self.my_loop(self.address)
  8325. @pyqtSlot()
  8326. def close_listener(self):
  8327. self.thread_exit = True
  8328. self.listener.close()
  8329. # end of file