app_Main.py 453 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116
  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.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from appEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from appEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from appEditors.FlatCAMTextEditor import TextEditor
  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.993
  137. version_date = "2020/06/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:
  168. # * App.info() --> Print on the status bar
  169. inform = QtCore.pyqtSignal([str], [str, bool])
  170. app_quit = QtCore.pyqtSignal()
  171. # General purpose background task
  172. worker_task = QtCore.pyqtSignal(dict)
  173. # File opened
  174. # Handled by:
  175. # * register_folder()
  176. # * register_recent()
  177. # Note: Setting the parameters to unicode does not seem
  178. # to have an effect. Then are received as Qstring
  179. # anyway.
  180. # File type and filename
  181. file_opened = QtCore.pyqtSignal(str, str)
  182. # File type and filename
  183. file_saved = QtCore.pyqtSignal(str, str)
  184. # Percentage of progress
  185. progress = QtCore.pyqtSignal(int)
  186. # Emitted when a new object has been added or deleted from/to the collection
  187. object_status_changed = QtCore.pyqtSignal(object, str, str)
  188. message = QtCore.pyqtSignal(str, str, str)
  189. # Emmited when shell command is finished(one command only)
  190. shell_command_finished = QtCore.pyqtSignal(object)
  191. # Emitted when multiprocess pool has been recreated
  192. pool_recreated = QtCore.pyqtSignal(object)
  193. # Emitted when an unhandled exception happens
  194. # in the worker task.
  195. thread_exception = QtCore.pyqtSignal(object)
  196. # used to signal that there are arguments for the app
  197. args_at_startup = QtCore.pyqtSignal(list)
  198. # a reusable signal to replot a list of objects
  199. # should be disconnected after use so it can be reused
  200. replot_signal = pyqtSignal(list)
  201. # signal emitted when jumping
  202. jump_signal = pyqtSignal(tuple)
  203. # signal emitted when jumping
  204. locate_signal = pyqtSignal(tuple, str)
  205. # close app signal
  206. close_app_signal = pyqtSignal()
  207. # will perform the cleanup operation after a Graceful Exit
  208. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  209. # graphic residues behind
  210. cleanup = pyqtSignal()
  211. listen_th = QtCore.QThread()
  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. self.main_thread = QtWidgets.QApplication.instance().thread()
  221. # ############################################################################################################
  222. # ################# Setup the listening thread for another instance launching with args ######################
  223. # ############################################################################################################
  224. if sys.platform == 'win32' or sys.platform == 'linux':
  225. # make sure the thread is stored by using a self. otherwise it's garbage collected
  226. self.listen_th.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. # ###################################### Setting the Splash Screen ##########################################
  365. # ###########################################################################################################
  366. splash_settings = QSettings("Open Source", "FlatCAM")
  367. if splash_settings.contains("splash_screen"):
  368. show_splash = splash_settings.value("splash_screen")
  369. else:
  370. splash_settings.setValue('splash_screen', 1)
  371. # This will write the setting to the platform specific storage.
  372. del splash_settings
  373. show_splash = 1
  374. if show_splash and self.cmd_line_headless != 1:
  375. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  376. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  377. # self.splash.setMask(splash_pix.mask())
  378. # move splashscreen to the current monitor
  379. desktop = QtWidgets.QApplication.desktop()
  380. screen = desktop.screenNumber(QtGui.QCursor.pos())
  381. current_screen_center = desktop.availableGeometry(screen).center()
  382. self.splash.move(current_screen_center - self.splash.rect().center())
  383. self.splash.show()
  384. self.splash.showMessage(_("FlatCAM is initializing ..."),
  385. alignment=Qt.AlignBottom | Qt.AlignLeft,
  386. color=QtGui.QColor("gray"))
  387. else:
  388. show_splash = 0
  389. # ###########################################################################################################
  390. # ######################################### Initialize GUI ##################################################
  391. # ###########################################################################################################
  392. # FlatCAM colors used in plotting
  393. self.FC_light_green = '#BBF268BF'
  394. self.FC_dark_green = '#006E20BF'
  395. self.FC_light_blue = '#a5a5ffbf'
  396. self.FC_dark_blue = '#0000ffbf'
  397. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  398. if theme_settings.contains("theme"):
  399. theme = theme_settings.value('theme', type=str)
  400. else:
  401. theme = 'white'
  402. if self.defaults["global_cursor_color_enabled"]:
  403. self.cursor_color_3D = self.defaults["global_cursor_color"]
  404. else:
  405. if theme == 'white':
  406. self.cursor_color_3D = 'black'
  407. else:
  408. self.cursor_color_3D = 'gray'
  409. # update the defaults dict with the setting in QSetting
  410. self.defaults['global_theme'] = theme
  411. self.ui = MainGUI(self)
  412. # set FlatCAM units in the Status bar
  413. self.set_screen_units(self.defaults['units'])
  414. # ###########################################################################################################
  415. # ########################################### AUTOSAVE SETUP ################################################
  416. # ###########################################################################################################
  417. self.block_autosave = False
  418. self.autosave_timer = QtCore.QTimer(self)
  419. self.save_project_auto_update()
  420. self.autosave_timer.timeout.connect(self.save_project_auto)
  421. # ###########################################################################################################
  422. # #################################### LOAD PREPROCESSORS ###################################################
  423. # ###########################################################################################################
  424. # ----------------------------------------- WARNING --------------------------------------------------------
  425. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  426. # That's because the number of preprocessors can vary and here the comboboxes are populated
  427. # -----------------------------------------------------------------------------------------------------------
  428. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  429. # the preprocessor file
  430. self.preprocessors = load_preprocessors(self)
  431. # make sure that always the 'default' preprocessor is the first item in the dictionary
  432. if 'default' in self.preprocessors.keys():
  433. new_ppp_dict = {}
  434. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  435. default_pp = self.preprocessors.pop('default')
  436. new_ppp_dict['default'] = default_pp
  437. # then add the rest of the keys
  438. for name, val_class in self.preprocessors.items():
  439. new_ppp_dict[name] = val_class
  440. # and now put back the ordered dict with 'default' key first
  441. self.preprocessors = new_ppp_dict
  442. for name in list(self.preprocessors.keys()):
  443. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  444. if name.partition('_')[0] == 'Paste':
  445. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  446. continue
  447. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  448. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  449. if name == 'hpgl':
  450. continue
  451. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  452. # ###########################################################################################################
  453. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  454. # ###########################################################################################################
  455. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  456. inform=self.inform)
  457. self.preferencesUiManager.defaults_write_form()
  458. # When the self.defaults dictionary changes will update the Preferences GUI forms
  459. self.defaults.set_change_callback(self.on_defaults_dict_change)
  460. # ###########################################################################################################
  461. # ##################################### FIRST RUN SECTION ###################################################
  462. # ################################ It's done only once after install #####################################
  463. # ###########################################################################################################
  464. if self.defaults["first_run"] is True:
  465. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  466. initial_lay = 'minimal'
  467. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  468. # Set the combobox in Preferences to the current layout
  469. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  470. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  471. # after the first run, this object should be False
  472. self.defaults["first_run"] = False
  473. self.preferencesUiManager.save_defaults(silent=True)
  474. # ###########################################################################################################
  475. # ############################################ Data #########################################################
  476. # ###########################################################################################################
  477. self.recent = []
  478. self.recent_projects = []
  479. self.clipboard = QtWidgets.QApplication.clipboard()
  480. self.project_filename = None
  481. self.toggle_units_ignore = False
  482. # ###########################################################################################################
  483. # ########################################## LOAD LANGUAGES ################################################
  484. # ###########################################################################################################
  485. self.languages = fcTranslate.load_languages()
  486. for name in sorted(self.languages.values()):
  487. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  488. # ###########################################################################################################
  489. # ####################################### APPLY APP LANGUAGE ################################################
  490. # ###########################################################################################################
  491. ret_val = fcTranslate.apply_language('strings')
  492. if ret_val == "no language":
  493. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  494. log.debug("Could not find the Language files. The App strings are missing.")
  495. else:
  496. # make the current language the current selection on the language combobox
  497. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  498. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  499. # ###########################################################################################################
  500. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  501. # ###########################################################################################################
  502. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  503. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  504. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  505. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  506. self.defaults.propagate_defaults()
  507. # ###########################################################################################################
  508. # ######################################## UPDATE THE OPTIONS ###############################################
  509. # ###########################################################################################################
  510. self.options = LoudDict()
  511. # -----------------------------------------------------------------------------------------------------------
  512. # Update the self.options from the self.defaults
  513. # The self.defaults holds the application defaults while the self.options holds the object defaults
  514. # -----------------------------------------------------------------------------------------------------------
  515. # Copy app defaults to project options
  516. for def_key, def_val in self.defaults.items():
  517. self.options[def_key] = deepcopy(def_val)
  518. self.preferencesUiManager.show_preferences_gui()
  519. # ### End of Data ####
  520. # ###########################################################################################################
  521. # #################################### SETUP OBJECT COLLECTION ##############################################
  522. # ###########################################################################################################
  523. self.collection = ObjectCollection(app=self)
  524. self.ui.project_tab_layout.addWidget(self.collection.view)
  525. self.app_obj = AppObject(app=self)
  526. # ### Adjust tabs width ## ##
  527. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  528. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  529. self.collection.view.setMinimumWidth(290)
  530. self.log.debug("Finished creating Object Collection.")
  531. # ###########################################################################################################
  532. # ######################################## SETUP Plot Area ##################################################
  533. # ###########################################################################################################
  534. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  535. if self.defaults["global_graphic_engine"] == '3D':
  536. self.is_legacy = False
  537. else:
  538. self.is_legacy = True
  539. # Event signals disconnect id holders
  540. self.mp = None
  541. self.mm = None
  542. self.mr = None
  543. self.mdc = None
  544. self.mp_zc = None
  545. self.kp = None
  546. # Matplotlib axis
  547. self.axes = None
  548. if show_splash:
  549. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  550. "Canvas initialization started."),
  551. alignment=Qt.AlignBottom | Qt.AlignLeft,
  552. color=QtGui.QColor("gray"))
  553. start_plot_time = time.time() # debug
  554. self.plotcanvas = None
  555. self.app_cursor = None
  556. self.hover_shapes = None
  557. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  558. # setup the PlotCanvas
  559. self.on_plotcanvas_setup()
  560. end_plot_time = time.time()
  561. self.used_time = end_plot_time - start_plot_time
  562. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  563. if show_splash:
  564. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  565. "Canvas initialization started.\n"
  566. "Canvas initialization finished in"), '%.2f' % self.used_time),
  567. alignment=Qt.AlignBottom | Qt.AlignLeft,
  568. color=QtGui.QColor("gray"))
  569. self.ui.splitter.setStretchFactor(1, 2)
  570. # ###########################################################################################################
  571. # ############################################### SYS TRAY ##################################################
  572. # ###########################################################################################################
  573. if self.defaults["global_systray_icon"]:
  574. self.parent_w = QtWidgets.QWidget()
  575. if self.cmd_line_headless == 1:
  576. self.trayIcon = FlatCAMSystemTray(app=self,
  577. icon=QtGui.QIcon(self.resource_location +
  578. '/flatcam_icon32_green.png'),
  579. headless=True,
  580. parent=self.parent_w)
  581. else:
  582. self.trayIcon = FlatCAMSystemTray(app=self,
  583. icon=QtGui.QIcon(self.resource_location +
  584. '/flatcam_icon32_green.png'),
  585. parent=self.parent_w)
  586. # ###########################################################################################################
  587. # ############################################### Worker SETUP ##############################################
  588. # ###########################################################################################################
  589. if self.defaults["global_worker_number"]:
  590. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  591. else:
  592. self.workers = WorkerStack(workers_number=2)
  593. self.worker_task.connect(self.workers.add_task)
  594. self.log.debug("Finished creating Workers crew.")
  595. # ###########################################################################################################
  596. # ############################################# Activity Monitor ###########################################
  597. # ###########################################################################################################
  598. self.activity_view = FlatCAMActivityView(app=self)
  599. self.ui.infobar.addWidget(self.activity_view)
  600. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  601. # ###########################################################################################################
  602. # ############################################# Signal handling #############################################
  603. # ###########################################################################################################
  604. # ########################################## Custom signals ################################################
  605. # signal for displaying messages in status bar
  606. self.inform[str].connect(self.info)
  607. self.inform[str, bool].connect(self.info)
  608. # signal to be called when the app is quiting
  609. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  610. self.message.connect(lambda: message_dialog(parent=self.ui))
  611. # self.progress.connect(self.set_progress_bar)
  612. # signals emitted when file state change
  613. self.file_opened.connect(self.register_recent)
  614. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  615. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  616. # ########################################## Standard signals ###############################################
  617. # ### Menu
  618. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  619. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  620. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  621. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  622. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  623. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  624. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  625. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  626. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  627. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  628. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  629. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  630. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  631. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  632. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  633. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  634. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  635. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  636. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  637. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  638. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  639. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  640. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  641. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  642. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  643. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  644. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  645. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  646. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  647. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  648. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  649. self.ui.menufile_exit.triggered.connect(self.final_save)
  650. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  651. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  652. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  653. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  654. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  655. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  656. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  657. self.ui.menueditdelete.triggered.connect(self.on_delete)
  658. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  659. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  660. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  661. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  662. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  663. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  664. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  665. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  666. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  667. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  668. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  669. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  670. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  671. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  672. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  673. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  674. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  675. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  676. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  677. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  678. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  679. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  680. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  681. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  682. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  683. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  684. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  685. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  686. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  687. self.ui.menuview_replot.triggered.connect(self.plot_all)
  688. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  689. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  690. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  691. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  692. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  693. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  696. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  697. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  698. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  699. self.ui.menuhelp_about.triggered.connect(self.on_about)
  700. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  701. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  702. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  703. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  704. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  705. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  706. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  707. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  708. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  709. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  710. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  711. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  712. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  713. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  714. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  715. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  716. # ToolBar signals
  717. self.connect_toolbar_signals()
  718. # Notebook and Plot Tab Area signals
  719. # make the right click on the notebook tab and plot tab area tab raise a menu
  720. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  722. self.on_tab_setup_context_menu()
  723. # activate initial state
  724. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  725. # Context Menu
  726. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  727. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  728. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  729. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  730. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  731. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  732. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  733. self.ui.clearplot.triggered.connect(self.clear_plots)
  734. self.ui.replot.triggered.connect(self.plot_all)
  735. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  736. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  737. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  738. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  739. self.ui.popmenu_move.triggered.connect(self.obj_move)
  740. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  741. # Project Context Menu -> Color Setting
  742. for act in self.ui.menuprojectcolor.actions():
  743. act.triggered.connect(self.on_set_color_action_triggered)
  744. # ###########################################################################################################
  745. # #################################### GUI PREFERENCES SIGNALS ##############################################
  746. # ###########################################################################################################
  747. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  748. lambda: self.on_toggle_units(no_pref=False))
  749. # ##################################### Workspace Setting Signals ###########################################
  750. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  751. self.on_workspace_modified)
  752. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  753. self.on_workspace_modified
  754. )
  755. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  756. # ###########################################################################################################
  757. # ######################################## GUI SETTINGS SIGNALS #############################################
  758. # ###########################################################################################################
  759. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  760. # ######################################## Tools related signals ############################################
  761. # portability changed signal
  762. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  763. # Object list
  764. self.object_status_changed.connect(self.collection.on_collection_updated)
  765. # when there are arguments at application startup this get launched
  766. self.args_at_startup[list].connect(self.on_startup_args)
  767. # ###########################################################################################################
  768. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  769. # ###########################################################################################################
  770. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  771. lambda: self.restore_extensions(ext_type='excellon'))
  772. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  773. lambda: self.restore_extensions(ext_type='gcode'))
  774. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  775. lambda: self.restore_extensions(ext_type='gerber'))
  776. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  777. lambda: self.delete_all_extensions(ext_type='excellon'))
  778. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  779. lambda: self.delete_all_extensions(ext_type='gcode'))
  780. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  781. lambda: self.delete_all_extensions(ext_type='gerber'))
  782. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  783. lambda: self.add_extension(ext_type='excellon'))
  784. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  785. lambda: self.add_extension(ext_type='gcode'))
  786. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  787. lambda: self.add_extension(ext_type='gerber'))
  788. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  789. lambda: self.del_extension(ext_type='excellon'))
  790. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  791. lambda: self.del_extension(ext_type='gcode'))
  792. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  793. lambda: self.del_extension(ext_type='gerber'))
  794. # connect the 'Apply' buttons from the Preferences/File Associations
  795. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  796. lambda: self.on_register_files(obj_type='excellon'))
  797. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  798. lambda: self.on_register_files(obj_type='gcode'))
  799. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  800. lambda: self.on_register_files(obj_type='gerber'))
  801. # ###########################################################################################################
  802. # ########################################### KEYWORDS SIGNALS ##############################################
  803. # ###########################################################################################################
  804. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  805. lambda: self.restore_extensions(ext_type='keyword'))
  806. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  807. lambda: self.delete_all_extensions(ext_type='keyword'))
  808. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  809. lambda: self.add_extension(ext_type='keyword'))
  810. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='keyword'))
  812. # ###########################################################################################################
  813. # ########################################### GUI SIGNALS ###################################################
  814. # ###########################################################################################################
  815. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  816. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  817. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  818. # ###########################################################################################################
  819. # ####################################### VARIOUS SIGNALS ###################################################
  820. # ###########################################################################################################
  821. # connect the abort_all_tasks related slots to the related signals
  822. self.proc_container.idle_flag.connect(self.app_is_idle)
  823. # signal emitted when a tab is closed in the Plot Area
  824. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  825. # signal to close the application
  826. self.close_app_signal.connect(self.kill_app)
  827. # ################################# FINISHED CONNECTING SIGNALS #############################################
  828. # ###########################################################################################################
  829. # ###########################################################################################################
  830. # ###########################################################################################################
  831. self.log.debug("Finished connecting Signals.")
  832. # ###########################################################################################################
  833. # ########################################## Other setups ###################################################
  834. # ###########################################################################################################
  835. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  836. # depending on from where those tools are called different actions can be done
  837. self.call_source = 'app'
  838. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  839. self.tool_tab_locked = False
  840. # decide if to show or hide the Notebook side of the screen at startup
  841. if self.defaults["global_project_at_startup"] is True:
  842. self.ui.splitter.setSizes([1, 1])
  843. else:
  844. self.ui.splitter.setSizes([0, 1])
  845. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  846. self.setup_component_editor()
  847. # ###########################################################################################################
  848. # ####################################### Auto-complete KEYWORDS ############################################
  849. # ###########################################################################################################
  850. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  851. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  852. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  853. 'export_exc',
  854. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  855. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  856. 'interiors', 'isolate', 'join_excellon',
  857. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  858. 'mirror', 'ncc',
  859. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  860. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  861. 'options', 'origin',
  862. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  863. 'save', 'save_project',
  864. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  865. 'skew', 'subtract_poly', 'subtract_rectangle',
  866. 'version', 'write_gcode'
  867. ]
  868. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  869. 'Paste_1',
  870. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  871. 'Toolchange_manual', 'True', 'Users',
  872. 'all', 'auto', 'axis',
  873. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  874. 'contour', 'default',
  875. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  876. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  877. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  878. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  879. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  880. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  881. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  882. 'spacing_columns',
  883. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  884. 'toolchange_xy', 'toolchangez', 'travelz',
  885. 'tooldia', 'use_threads', 'value',
  886. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  887. ]
  888. self.tcl_keywords = [
  889. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  890. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  891. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  892. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  893. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  894. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  895. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  896. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  897. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  898. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  899. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  900. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  901. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  902. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  903. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  904. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  905. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  906. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  907. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  908. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  909. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  910. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  911. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  912. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  913. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  914. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  915. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  916. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  917. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  918. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  919. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  920. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  921. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  922. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  923. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  924. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  925. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  926. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  927. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  928. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  929. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  930. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  931. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  932. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  933. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  934. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  935. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  936. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  937. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  938. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  939. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  940. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  941. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  942. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  943. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  944. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  945. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  946. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  947. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  948. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  949. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  950. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  951. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  952. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  953. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  954. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  955. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  956. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  957. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  958. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  959. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  960. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  961. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  962. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  963. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  964. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  965. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  966. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  967. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  968. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  969. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  970. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  971. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  972. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  973. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  974. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  975. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  976. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  977. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  978. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  979. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  980. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  981. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  982. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  983. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  984. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  985. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  986. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  987. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  988. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  989. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  990. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  991. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  992. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  993. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  994. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  995. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  996. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  997. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  998. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  999. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1000. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1001. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1002. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1003. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1004. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1005. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1006. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1007. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1008. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1009. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1010. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1011. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1012. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1013. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1014. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1015. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1016. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1017. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1018. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1019. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1020. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1021. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1022. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1023. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1024. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1025. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1026. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1027. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1028. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1029. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1030. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1031. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1032. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1033. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1034. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1035. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1036. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1037. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1038. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1039. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1040. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1041. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1042. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1043. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1044. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1045. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1046. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1047. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1048. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1049. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1050. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1051. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1052. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1053. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1054. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1055. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1056. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1057. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1058. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1059. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1060. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1061. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1062. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1063. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1064. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1065. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1066. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1067. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1068. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1069. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1070. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1071. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1072. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1073. ]
  1074. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1075. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1076. # ###########################################################################################################
  1077. # ############################################## Shell SETUP ################################################
  1078. # ###########################################################################################################
  1079. self.shell = FCShell(app=self, version=self.version)
  1080. self.ui.shell_dock.setWidget(self.shell)
  1081. self.log.debug("TCL Shell has been initialized.")
  1082. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1083. if self.defaults["global_shell_at_startup"]:
  1084. self.ui.shell_dock.show()
  1085. else:
  1086. self.ui.shell_dock.hide()
  1087. # ###########################################################################################################
  1088. # ########################################## Tools and Plugins ##############################################
  1089. # ###########################################################################################################
  1090. self.dblsidedtool = None
  1091. self.distance_tool = None
  1092. self.distance_min_tool = None
  1093. self.panelize_tool = None
  1094. self.film_tool = None
  1095. self.paste_tool = None
  1096. self.calculator_tool = None
  1097. self.rules_tool = None
  1098. self.sub_tool = None
  1099. self.move_tool = None
  1100. self.cutout_tool = None
  1101. self.ncclear_tool = None
  1102. self.paint_tool = None
  1103. self.isolation_tool = None
  1104. self.optimal_tool = None
  1105. self.transform_tool = None
  1106. self.properties_tool = None
  1107. self.pdf_tool = None
  1108. self.image_tool = None
  1109. self.pcb_wizard_tool = None
  1110. self.cal_exc_tool = None
  1111. self.qrcode_tool = None
  1112. self.copper_thieving_tool = None
  1113. self.fiducial_tool = None
  1114. self.edrills_tool = None
  1115. self.align_objects_tool = None
  1116. self.punch_tool = None
  1117. self.invert_tool = None
  1118. self.corners_tool = None
  1119. self.etch_tool = None
  1120. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1121. try:
  1122. self.install_tools()
  1123. except AttributeError as e:
  1124. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1125. # ###########################################################################################################
  1126. # ############################################ SETUP RECENT ITEMS ###########################################
  1127. # ###########################################################################################################
  1128. self.setup_recent_items()
  1129. # ###########################################################################################################
  1130. # ######################################### BookMarks Manager ###############################################
  1131. # ###########################################################################################################
  1132. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1133. self.install_bookmarks()
  1134. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1135. # ###########################################################################################################
  1136. # ########################################### Tools Database ################################################
  1137. # ###########################################################################################################
  1138. self.tools_db_tab = None
  1139. # ### System Font Parsing ###
  1140. # self.f_parse = ParseFont(self)
  1141. # self.parse_system_fonts()
  1142. # ###########################################################################################################
  1143. # ######################################### Check for updates ###############################################
  1144. # ###########################################################################################################
  1145. # Separate thread (Not worker)
  1146. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1147. if (self.beta is False or self.beta is None) and \
  1148. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1149. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1150. # self.thr2 = QtCore.QThread()
  1151. self.worker_task.emit({'fcn': self.version_check,
  1152. 'params': []})
  1153. # self.thr2.start(QtCore.QThread.LowPriority)
  1154. # ###########################################################################################################
  1155. # ##################################### Register files with FlatCAM; #######################################
  1156. # ################################### It works only for Windows for now ####################################
  1157. # ###########################################################################################################
  1158. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1159. self.on_register_files()
  1160. # ###########################################################################################################
  1161. # ######################################## Variables for global usage #######################################
  1162. # ###########################################################################################################
  1163. # hold the App units
  1164. self.units = 'MM'
  1165. # coordinates for relative position display
  1166. self.rel_point1 = (0, 0)
  1167. self.rel_point2 = (0, 0)
  1168. # variable to store coordinates
  1169. self.pos = (0, 0)
  1170. self.pos_canvas = (0, 0)
  1171. self.pos_jump = (0, 0)
  1172. # variable to store mouse coordinates
  1173. self.mouse = [0, 0]
  1174. # variable to store the delta positions on cavnas
  1175. self.dx = 0
  1176. self.dy = 0
  1177. # decide if we have a double click or single click
  1178. self.doubleclick = False
  1179. # store here the is_dragging value
  1180. self.event_is_dragging = False
  1181. # variable to store if a command is active (then the var is not None) and which one it is
  1182. self.command_active = None
  1183. # variable to store the status of moving selection action
  1184. # None value means that it's not an selection action
  1185. # True value = a selection from left to right
  1186. # False value = a selection from right to left
  1187. self.selection_type = None
  1188. # List to store the objects that are currently loaded in FlatCAM
  1189. # This list is updated on each object creation or object delete
  1190. self.all_objects_list = []
  1191. self.objects_under_the_click_list = []
  1192. # List to store the objects that are selected
  1193. self.sel_objects_list = []
  1194. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1195. self.key_modifiers = None
  1196. # Variable to store the status of the code editor
  1197. self.toggle_codeeditor = False
  1198. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1199. self.click_noproject = False
  1200. self.cursor = None
  1201. # Variable to store the GCODE that was edited
  1202. self.gcode_edited = ""
  1203. self.text_editor_tab = None
  1204. # reference for the self.ui.code_editor
  1205. self.reference_code_editor = None
  1206. self.script_code = ''
  1207. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1208. self.tools_db_changed_flag = False
  1209. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1210. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1211. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1212. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1213. 'tsm']
  1214. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1215. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1216. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1217. 'sbp', 'tap', 'xpi']
  1218. self.svg_list = ['svg']
  1219. self.dxf_list = ['dxf']
  1220. self.pdf_list = ['pdf']
  1221. self.prj_list = ['flatprj']
  1222. self.conf_list = ['flatconfig']
  1223. # last used filters
  1224. self.last_op_gerber_filter = None
  1225. self.last_op_excellon_filter = None
  1226. self.last_op_gcode_filter = None
  1227. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1228. # flag for polygons not cleared
  1229. self.poly_not_cleared = False
  1230. # VisPy visuals
  1231. self.isHovering = False
  1232. self.notHovering = True
  1233. # Window geometry
  1234. self.x_pos = None
  1235. self.y_pos = None
  1236. self.width = None
  1237. self.height = None
  1238. # when True, the app has to return from any thread
  1239. self.abort_flag = False
  1240. # set the value used in the Windows Title
  1241. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1242. # this holds a widget that is installed in the Plot Area when View Source option is used
  1243. self.source_editor_tab = None
  1244. self.pagesize = {}
  1245. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1246. # VisPy visuals
  1247. if self.is_legacy is False:
  1248. try:
  1249. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1250. except AttributeError:
  1251. self.tool_shapes = None
  1252. else:
  1253. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1254. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1255. # used in the delayed shutdown self.start_delayed_quit() method
  1256. self.save_timer = None
  1257. # ###########################################################################################################
  1258. # ################################## ADDING FlatCAM EDITORS section #########################################
  1259. # ###########################################################################################################
  1260. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1261. # at the first launch of the App , the editors will not be functional.
  1262. try:
  1263. self.geo_editor = FlatCAMGeoEditor(self)
  1264. except Exception as es:
  1265. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1266. try:
  1267. self.exc_editor = FlatCAMExcEditor(self)
  1268. except Exception as es:
  1269. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1270. try:
  1271. self.grb_editor = FlatCAMGrbEditor(self)
  1272. except Exception as es:
  1273. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1274. self.log.debug("Finished adding FlatCAM Editor's.")
  1275. self.set_ui_title(name=_("New Project - Not saved"))
  1276. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1277. current_platform = platform.architecture()[0]
  1278. if current_platform != '64bit':
  1279. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1280. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1281. # ###########################################################################################################
  1282. # ########################################### EXCLUSION AREAS ###############################################
  1283. # ###########################################################################################################
  1284. self.exc_areas = ExclusionAreas(app=self)
  1285. # ###########################################################################################################
  1286. # ##################################### Finished the CONSTRUCTOR ############################################
  1287. # ###########################################################################################################
  1288. App.log.debug("END of constructor. Releasing control.")
  1289. # ###########################################################################################################
  1290. # ########################################## SHOW GUI #######################################################
  1291. # ###########################################################################################################
  1292. # if the app is not started as headless, show it
  1293. if self.cmd_line_headless != 1:
  1294. if show_splash:
  1295. # finish the splash
  1296. self.splash.finish(self.ui)
  1297. mgui_settings = QSettings("Open Source", "FlatCAM")
  1298. if mgui_settings.contains("maximized_gui"):
  1299. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1300. if maximized_ui is True:
  1301. self.ui.showMaximized()
  1302. else:
  1303. self.ui.show()
  1304. else:
  1305. self.ui.show()
  1306. if self.defaults["global_systray_icon"]:
  1307. self.trayIcon.show()
  1308. else:
  1309. log.warning("******************* RUNNING HEADLESS *******************")
  1310. # ###########################################################################################################
  1311. # ######################################## START-UP ARGUMENTS ###############################################
  1312. # ###########################################################################################################
  1313. # test if the program was started with a script as parameter
  1314. if self.cmd_line_shellvar:
  1315. try:
  1316. cnt = 0
  1317. command_tcl = 0
  1318. for i in self.cmd_line_shellvar.split(','):
  1319. if i is not None:
  1320. # noinspection PyBroadException
  1321. try:
  1322. command_tcl = eval(i)
  1323. except Exception:
  1324. command_tcl = i
  1325. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1326. cnt += 1
  1327. # if there are Windows paths then replace the path separator with a Unix like one
  1328. if sys.platform == 'win32':
  1329. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1330. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1331. except Exception as ext:
  1332. print("ERROR: ", ext)
  1333. sys.exit(2)
  1334. if self.cmd_line_shellfile:
  1335. if self.cmd_line_headless != 1:
  1336. if self.ui.shell_dock.isHidden():
  1337. self.ui.shell_dock.show()
  1338. try:
  1339. with open(self.cmd_line_shellfile, "r") as myfile:
  1340. # if show_splash:
  1341. # self.splash.showMessage('%s: %ssec\n%s' % (
  1342. # _("Canvas initialization started.\n"
  1343. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1344. # _("Executing Tcl Script ...")),
  1345. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1346. # color=QtGui.QColor("gray"))
  1347. cmd_line_shellfile_text = myfile.read()
  1348. if self.cmd_line_headless != 1:
  1349. self.shell.exec_command(cmd_line_shellfile_text)
  1350. else:
  1351. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1352. except Exception as ext:
  1353. print("ERROR: ", ext)
  1354. sys.exit(2)
  1355. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1356. # the path/file_name must be enclosed in quotes if it contain spaces
  1357. if App.args:
  1358. self.args_at_startup.emit(App.args)
  1359. if self.defaults.old_defaults_found is True:
  1360. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1361. "Please reboot the application to update."))
  1362. self.defaults.old_defaults_found = False
  1363. # ######################################### INIT FINISHED #######################################################
  1364. # #################################################################################################################
  1365. # #################################################################################################################
  1366. # #################################################################################################################
  1367. # #################################################################################################################
  1368. # #################################################################################################################
  1369. @staticmethod
  1370. def copy_and_overwrite(from_path, to_path):
  1371. """
  1372. From here:
  1373. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1374. :param from_path: source path
  1375. :param to_path: destination path
  1376. :return: None
  1377. """
  1378. if os.path.exists(to_path):
  1379. shutil.rmtree(to_path)
  1380. try:
  1381. shutil.copytree(from_path, to_path)
  1382. except FileNotFoundError:
  1383. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1384. shutil.copytree(from_new_path, to_path)
  1385. def on_startup_args(self, args, silent=False):
  1386. """
  1387. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1388. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1389. :param args: a list containing the application args at startup
  1390. :return: None
  1391. """
  1392. if args is not None:
  1393. args_to_process = args
  1394. else:
  1395. args_to_process = App.args
  1396. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1397. for argument in args_to_process:
  1398. if '.FlatPrj'.lower() in argument.lower():
  1399. try:
  1400. project_name = str(argument)
  1401. if project_name == "":
  1402. if silent is False:
  1403. self.inform.emit(_("Cancelled."))
  1404. else:
  1405. # self.open_project(project_name)
  1406. run_from_arg = True
  1407. # self.worker_task.emit({'fcn': self.open_project,
  1408. # 'params': [project_name, run_from_arg]})
  1409. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1410. except Exception as e:
  1411. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1412. elif '.FlatConfig'.lower() in argument.lower():
  1413. try:
  1414. file_name = str(argument)
  1415. if file_name == "":
  1416. if silent is False:
  1417. self.inform.emit(_("Open Config file failed."))
  1418. else:
  1419. run_from_arg = True
  1420. # self.worker_task.emit({'fcn': self.open_config_file,
  1421. # 'params': [file_name, run_from_arg]})
  1422. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1423. except Exception as e:
  1424. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1425. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1426. try:
  1427. file_name = str(argument)
  1428. if file_name == "":
  1429. if silent is False:
  1430. self.inform.emit(_("Open Script file failed."))
  1431. else:
  1432. if silent is False:
  1433. self.on_fileopenscript(name=file_name)
  1434. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1435. self.on_filerunscript(name=file_name)
  1436. except Exception as e:
  1437. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1438. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1439. log.debug("App.on_startup_args() --> Quit event.")
  1440. sys.exit()
  1441. elif 'save'.lower() in argument.lower():
  1442. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1443. self.preferencesUiManager.save_defaults()
  1444. else:
  1445. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1446. proc_arg = argument.lower()
  1447. for ext in exc_list:
  1448. proc_ext = ext.replace(' ', '')
  1449. proc_ext = '.%s' % proc_ext
  1450. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1451. file_name = str(argument)
  1452. if file_name == "":
  1453. if silent is False:
  1454. self.inform.emit(_("Open Excellon file failed."))
  1455. else:
  1456. self.on_fileopenexcellon(name=file_name, signal=None)
  1457. return
  1458. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1459. for ext in gco_list:
  1460. proc_ext = ext.replace(' ', '')
  1461. proc_ext = '.%s' % proc_ext
  1462. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1463. file_name = str(argument)
  1464. if file_name == "":
  1465. if silent is False:
  1466. self.inform.emit(_("Open GCode file failed."))
  1467. else:
  1468. self.on_fileopengcode(name=file_name, signal=None)
  1469. return
  1470. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1471. for ext in grb_list:
  1472. proc_ext = ext.replace(' ', '')
  1473. proc_ext = '.%s' % proc_ext
  1474. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1475. file_name = str(argument)
  1476. if file_name == "":
  1477. if silent is False:
  1478. self.inform.emit(_("Open Gerber file failed."))
  1479. else:
  1480. self.on_fileopengerber(name=file_name, signal=None)
  1481. return
  1482. # if it reached here without already returning then the app was registered with a file that it does not
  1483. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1484. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1485. # for arg in args_to_process:
  1486. # if 'FlatCAM.exe' in arg:
  1487. # continue
  1488. # else:
  1489. # sys.exit(2)
  1490. def set_ui_title(self, name):
  1491. """
  1492. Sets the title of the main window.
  1493. :param name: String that store the project path and project name
  1494. :return: None
  1495. """
  1496. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1497. (self.version,
  1498. ('BETA' if self.beta else ''),
  1499. platform.architecture()[0],
  1500. self.engine,
  1501. name)
  1502. )
  1503. def on_app_restart(self):
  1504. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1505. # be left in the SySTray
  1506. try:
  1507. self.trayIcon.hide()
  1508. except Exception:
  1509. pass
  1510. fcTranslate.restart_program(app=self)
  1511. def clear_pool(self):
  1512. """
  1513. Clear the multiprocessing pool and calls garbage collector.
  1514. :return: None
  1515. """
  1516. self.pool.close()
  1517. self.pool = Pool()
  1518. self.pool_recreated.emit(self.pool)
  1519. gc.collect()
  1520. def install_tools(self):
  1521. """
  1522. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1523. Instantiation of the Tools classes.
  1524. The order that the tools are installed is important as they can depend on each other install position.
  1525. :return: None
  1526. """
  1527. self.distance_tool = Distance(self)
  1528. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1529. before=self.ui.menueditorigin,
  1530. separator=False)
  1531. self.distance_min_tool = DistanceMin(self)
  1532. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1533. pos=self.ui.menuedit,
  1534. before=self.ui.menueditorigin,
  1535. separator=True)
  1536. self.dblsidedtool = DblSidedTool(self)
  1537. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1538. self.cal_exc_tool = ToolCalibration(self)
  1539. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1540. before=self.dblsidedtool.menuAction,
  1541. separator=False)
  1542. self.align_objects_tool = AlignObjects(self)
  1543. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1544. self.edrills_tool = ToolExtractDrills(self)
  1545. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1546. self.panelize_tool = Panelize(self)
  1547. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1548. self.film_tool = Film(self)
  1549. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1550. self.paste_tool = SolderPaste(self)
  1551. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1552. self.calculator_tool = ToolCalculator(self)
  1553. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1554. self.sub_tool = ToolSub(self)
  1555. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1556. pos=self.ui.menutool, separator=True)
  1557. self.rules_tool = RulesCheck(self)
  1558. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1559. pos=self.ui.menutool, separator=False)
  1560. self.optimal_tool = ToolOptimal(self)
  1561. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1562. pos=self.ui.menutool, separator=True)
  1563. self.move_tool = ToolMove(self)
  1564. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1565. before=self.ui.menueditorigin, separator=True)
  1566. self.cutout_tool = CutOut(self)
  1567. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1568. before=self.sub_tool.menuAction)
  1569. self.ncclear_tool = NonCopperClear(self)
  1570. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1571. before=self.sub_tool.menuAction, separator=True)
  1572. self.paint_tool = ToolPaint(self)
  1573. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1574. before=self.sub_tool.menuAction, separator=True)
  1575. self.isolation_tool = ToolIsolation(self)
  1576. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1577. before=self.sub_tool.menuAction, separator=True)
  1578. self.copper_thieving_tool = ToolCopperThieving(self)
  1579. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1580. pos=self.ui.menutool)
  1581. self.fiducial_tool = ToolFiducials(self)
  1582. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1583. pos=self.ui.menutool)
  1584. self.qrcode_tool = QRCode(self)
  1585. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1586. pos=self.ui.menutool)
  1587. self.punch_tool = ToolPunchGerber(self)
  1588. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1589. self.invert_tool = ToolInvertGerber(self)
  1590. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1591. self.corners_tool = ToolCorners(self)
  1592. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1593. self.etch_tool = ToolEtchCompensation(self)
  1594. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1595. self.transform_tool = ToolTransform(self)
  1596. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1597. pos=self.ui.menuoptions, separator=True)
  1598. self.properties_tool = Properties(self)
  1599. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1600. pos=self.ui.menuoptions)
  1601. self.pdf_tool = ToolPDF(self)
  1602. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1603. pos=self.ui.menufileimport,
  1604. separator=True)
  1605. self.image_tool = ToolImage(self)
  1606. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1607. pos=self.ui.menufileimport,
  1608. separator=True)
  1609. self.pcb_wizard_tool = PcbWizard(self)
  1610. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1611. pos=self.ui.menufileimport)
  1612. self.log.debug("Tools are installed.")
  1613. def remove_tools(self):
  1614. """
  1615. Will remove all the actions in the Tool menu.
  1616. :return: None
  1617. """
  1618. for act in self.ui.menutool.actions():
  1619. self.ui.menutool.removeAction(act)
  1620. def init_tools(self):
  1621. """
  1622. Initialize the Tool tab in the notebook side of the central widget.
  1623. Remove the actions in the Tools menu.
  1624. Instantiate again the FlatCAM tools (plugins).
  1625. All this is required when changing the layout: standard, compact etc.
  1626. :return: None
  1627. """
  1628. log.debug("init_tools()")
  1629. # delete the data currently in the Tools Tab and the Tab itself
  1630. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1631. if widget is not None:
  1632. widget.deleteLater()
  1633. self.ui.notebook.removeTab(2)
  1634. # rebuild the Tools Tab
  1635. self.ui.tool_tab = QtWidgets.QWidget()
  1636. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1637. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1638. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1639. self.ui.tool_scroll_area = VerticalScrollArea()
  1640. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1641. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1642. # first remove all of them
  1643. self.remove_tools()
  1644. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1645. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1646. '&Command Line\tS')
  1647. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1648. # third install all of them
  1649. try:
  1650. self.install_tools()
  1651. except AttributeError:
  1652. pass
  1653. self.log.debug("Tools are initialized.")
  1654. # def parse_system_fonts(self):
  1655. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1656. # 'params': []})
  1657. def connect_toolbar_signals(self):
  1658. """
  1659. Reconnect the signals to the actions in the toolbar.
  1660. This has to be done each time after the FlatCAM tools are removed/installed.
  1661. :return: None
  1662. """
  1663. # Toolbar
  1664. # File Toolbar Signals
  1665. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1666. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1667. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1668. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1669. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1670. # View Toolbar Signals
  1671. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1672. self.ui.replot_btn.triggered.connect(self.plot_all)
  1673. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1674. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1675. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1676. # Edit Toolbar Signals
  1677. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1678. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1679. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1680. self.ui.delete_btn.triggered.connect(self.on_delete)
  1681. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1682. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1683. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1684. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1685. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1686. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1687. # Scripting Toolbar Signals
  1688. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1689. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1690. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1691. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1692. # Tools Toolbar Signals
  1693. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1694. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1695. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1696. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1697. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1698. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1699. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1700. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1701. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1702. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1703. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1704. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1705. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1706. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1707. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1708. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1709. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1710. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1711. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1712. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1713. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1714. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1715. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1716. def object2editor(self):
  1717. """
  1718. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1719. :return: None
  1720. """
  1721. self.defaults.report_usage("object2editor()")
  1722. # disable the objects menu as it may interfere with the appEditors
  1723. self.ui.menuobjects.setDisabled(True)
  1724. edited_object = self.collection.get_active()
  1725. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1726. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1727. pass
  1728. else:
  1729. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1730. return
  1731. if isinstance(edited_object, GeometryObject):
  1732. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1733. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1734. # we set the notebook to hidden
  1735. # self.ui.splitter.setSizes([0, 1])
  1736. if edited_object.multigeo is True:
  1737. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1738. if len(sel_rows) > 1:
  1739. self.inform.emit('[WARNING_NOTCL] %s' %
  1740. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1741. "is not possible.\n"
  1742. "Edit only one geometry at a time."))
  1743. # determine the tool dia of the selected tool
  1744. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1745. # now find the key in the edited_object.tools that has this tooldia
  1746. multi_tool = 1
  1747. for tool in edited_object.tools:
  1748. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1749. multi_tool = tool
  1750. break
  1751. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1752. else:
  1753. self.geo_editor.edit_fcgeometry(edited_object)
  1754. # set call source to the Editor we go into
  1755. self.call_source = 'geo_editor'
  1756. elif isinstance(edited_object, ExcellonObject):
  1757. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1758. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1759. if self.ui.splitter.sizes()[0] == 0:
  1760. self.ui.splitter.setSizes([1, 1])
  1761. self.exc_editor.edit_fcexcellon(edited_object)
  1762. # set call source to the Editor we go into
  1763. self.call_source = 'exc_editor'
  1764. elif isinstance(edited_object, GerberObject):
  1765. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1766. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1767. if self.ui.splitter.sizes()[0] == 0:
  1768. self.ui.splitter.setSizes([1, 1])
  1769. self.grb_editor.edit_fcgerber(edited_object)
  1770. # set call source to the Editor we go into
  1771. self.call_source = 'grb_editor'
  1772. # reset the following variables so the UI is built again after edit
  1773. edited_object.ui_build = False
  1774. edited_object.build_aperture_storage = False
  1775. elif isinstance(edited_object, CNCJobObject):
  1776. if self.ui.splitter.sizes()[0] == 0:
  1777. self.ui.splitter.setSizes([1, 1])
  1778. edited_object.on_edit_code_click()
  1779. return
  1780. # make sure that we can't select another object while in Editor Mode:
  1781. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1782. self.ui.project_frame.setDisabled(True)
  1783. # delete any selection shape that might be active as they are not relevant in Editor
  1784. self.delete_selection_shape()
  1785. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1786. self.ui.plot_tab_area.protectTab(0)
  1787. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1788. self.should_we_save = True
  1789. def editor2object(self, cleanup=None):
  1790. """
  1791. Transfers the Geometry or Excellon from it's editor to the current object.
  1792. :return: None
  1793. """
  1794. self.defaults.report_usage("editor2object()")
  1795. # re-enable the objects menu that was disabled on entry in Editor mode
  1796. self.ui.menuobjects.setDisabled(False)
  1797. # do not update a geometry or excellon object unless it comes out of an editor
  1798. if self.call_source != 'app':
  1799. edited_obj = self.collection.get_active()
  1800. if cleanup is None:
  1801. msgbox = QtWidgets.QMessageBox()
  1802. msgbox.setText(_("Do you want to save the edited object?"))
  1803. msgbox.setWindowTitle(_("Close Editor"))
  1804. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1805. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1806. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1807. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1808. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1809. msgbox.setDefaultButton(bt_yes)
  1810. msgbox.exec_()
  1811. response = msgbox.clickedButton()
  1812. if response == bt_yes:
  1813. # clean the Tools Tab
  1814. self.ui.tool_scroll_area.takeWidget()
  1815. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1816. self.ui.notebook.setTabText(2, "Tool")
  1817. if isinstance(edited_obj, GeometryObject):
  1818. obj_type = "Geometry"
  1819. self.geo_editor.update_fcgeometry(edited_obj)
  1820. # self.geo_editor.update_options(edited_obj)
  1821. # restore GUI to the Selected TAB
  1822. # Remove anything else in the appGUI
  1823. self.ui.tool_scroll_area.takeWidget()
  1824. # update the geo object options so it is including the bounding box values
  1825. try:
  1826. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1827. edited_obj.options['xmin'] = xmin
  1828. edited_obj.options['ymin'] = ymin
  1829. edited_obj.options['xmax'] = xmax
  1830. edited_obj.options['ymax'] = ymax
  1831. except AttributeError as e:
  1832. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1833. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1834. edited_obj.build_ui()
  1835. edited_obj.plot()
  1836. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1837. elif isinstance(edited_obj, GerberObject):
  1838. obj_type = "Gerber"
  1839. self.grb_editor.update_fcgerber()
  1840. # self.grb_editor.update_options(edited_obj)
  1841. # delete the old object (the source object) if it was an empty one
  1842. try:
  1843. if len(edited_obj.solid_geometry) == 0:
  1844. old_name = edited_obj.options['name']
  1845. self.collection.delete_by_name(old_name)
  1846. except TypeError:
  1847. # if the solid_geometry is a single Polygon the len() will not work
  1848. # in any case, falling here means that we have something in the solid_geometry, even if only
  1849. # a single Polygon, therefore we pass this
  1850. pass
  1851. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1852. # restore GUI to the Selected TAB
  1853. # Remove anything else in the appGUI
  1854. self.ui.selected_scroll_area.takeWidget()
  1855. elif isinstance(edited_obj, ExcellonObject):
  1856. obj_type = "Excellon"
  1857. self.exc_editor.update_fcexcellon(edited_obj)
  1858. # self.exc_editor.update_options(edited_obj)
  1859. # restore GUI to the Selected TAB
  1860. # Remove anything else in the appGUI
  1861. self.ui.tool_scroll_area.takeWidget()
  1862. # delete the old object (the source object) if it was an empty one
  1863. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1864. old_name = edited_obj.options['name']
  1865. self.collection.delete_by_name(name=old_name)
  1866. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1867. else:
  1868. self.inform.emit('[WARNING_NOTCL] %s' %
  1869. _("Select a Gerber, Geometry or Excellon Object to update."))
  1870. return
  1871. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1872. elif response == bt_no:
  1873. # clean the Tools Tab
  1874. self.ui.tool_scroll_area.takeWidget()
  1875. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1876. self.ui.notebook.setTabText(2, "Tool")
  1877. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1878. if isinstance(edited_obj, GeometryObject):
  1879. self.geo_editor.deactivate()
  1880. edited_obj.build_ui()
  1881. edited_obj.plot()
  1882. elif isinstance(edited_obj, GerberObject):
  1883. self.grb_editor.deactivate_grb_editor()
  1884. edited_obj.build_ui()
  1885. elif isinstance(edited_obj, ExcellonObject):
  1886. self.exc_editor.deactivate()
  1887. edited_obj.build_ui()
  1888. else:
  1889. self.inform.emit('[WARNING_NOTCL] %s' %
  1890. _("Select a Gerber, Geometry or Excellon Object to update."))
  1891. return
  1892. elif response == bt_cancel:
  1893. return
  1894. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1895. # edited_obj.build_ui()
  1896. # Switch notebook to Selected page
  1897. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1898. else:
  1899. if isinstance(edited_obj, GeometryObject):
  1900. self.geo_editor.deactivate()
  1901. elif isinstance(edited_obj, GerberObject):
  1902. self.grb_editor.deactivate_grb_editor()
  1903. elif isinstance(edited_obj, ExcellonObject):
  1904. self.exc_editor.deactivate()
  1905. else:
  1906. self.inform.emit('[WARNING_NOTCL] %s' %
  1907. _("Select a Gerber, Geometry or Excellon Object to update."))
  1908. return
  1909. # if notebook is hidden we show it
  1910. if self.ui.splitter.sizes()[0] == 0:
  1911. self.ui.splitter.setSizes([1, 1])
  1912. # restore the call_source to app
  1913. self.call_source = 'app'
  1914. # edited_obj.plot()
  1915. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1916. self.ui.plot_tab_area.protectTab(0)
  1917. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1918. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1919. self.ui.project_frame.setDisabled(False)
  1920. def get_last_folder(self):
  1921. """
  1922. Get the folder path from where the last file was opened.
  1923. :return: String, last opened folder path
  1924. """
  1925. return self.defaults["global_last_folder"]
  1926. def get_last_save_folder(self):
  1927. """
  1928. Get the folder path from where the last file was saved.
  1929. :return: String, last saved folder path
  1930. """
  1931. loc = self.defaults["global_last_save_folder"]
  1932. if loc is None:
  1933. loc = self.defaults["global_last_folder"]
  1934. if loc is None:
  1935. loc = os.path.dirname(__file__)
  1936. return loc
  1937. @QtCore.pyqtSlot(str)
  1938. @QtCore.pyqtSlot(str, bool)
  1939. def info(self, msg, shell_echo=True):
  1940. """
  1941. Informs the user. Normally on the status bar, optionally
  1942. also on the shell.
  1943. :param msg: Text to write.
  1944. :type msg: str
  1945. :param shell_echo: Control if to display the message msg in the Shell
  1946. :type shell_echo: bool
  1947. :return: None
  1948. """
  1949. # Type of message in brackets at the beginning of the message.
  1950. match = re.search(r"\[(.*)\](.*)", msg)
  1951. if match:
  1952. level = match.group(1)
  1953. msg_ = match.group(2)
  1954. self.ui.fcinfo.set_status(str(msg_), level=level)
  1955. if shell_echo is True:
  1956. if level.lower() == "error":
  1957. self.shell_message(msg, error=True, show=True)
  1958. elif level.lower() == "warning":
  1959. self.shell_message(msg, warning=True, show=True)
  1960. elif level.lower() == "error_notcl":
  1961. self.shell_message(msg, error=True, show=False)
  1962. elif level.lower() == "warning_notcl":
  1963. self.shell_message(msg, warning=True, show=False)
  1964. elif level.lower() == "success":
  1965. self.shell_message(msg, success=True, show=False)
  1966. elif level.lower() == "selected":
  1967. self.shell_message(msg, selected=True, show=False)
  1968. else:
  1969. self.shell_message(msg, show=False)
  1970. else:
  1971. self.ui.fcinfo.set_status(str(msg), level="info")
  1972. # make sure that if the message is to clear the infobar with a space
  1973. # is not printed over and over on the shell
  1974. if msg != '' and shell_echo is True:
  1975. self.shell_message(msg)
  1976. def on_import_preferences(self):
  1977. """
  1978. Loads the application default settings from a saved file into
  1979. ``self.defaults`` dictionary.
  1980. :return: None
  1981. """
  1982. self.defaults.report_usage("on_import_preferences")
  1983. App.log.debug("App.on_import_preferences()")
  1984. # Show file chooser
  1985. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1986. try:
  1987. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1988. directory=self.data_path,
  1989. filter=filter_)
  1990. except TypeError:
  1991. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1992. filter=filter_)
  1993. filename = str(filename)
  1994. if filename == "":
  1995. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1996. return
  1997. # Load in the defaults from the chosen file
  1998. self.defaults.load(filename=filename)
  1999. self.preferencesUiManager.on_preferences_edited()
  2000. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2001. def on_export_preferences(self):
  2002. """
  2003. Save the defaults dictionary to a file.
  2004. :return: None
  2005. """
  2006. self.defaults.report_usage("on_export_preferences")
  2007. App.log.debug("on_export_preferences()")
  2008. # defaults_file_content = None
  2009. # Show file chooser
  2010. date = str(datetime.today()).rpartition('.')[0]
  2011. date = ''.join(c for c in date if c not in ':-')
  2012. date = date.replace(' ', '_')
  2013. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2014. try:
  2015. filename, _f = FCFileSaveDialog.get_saved_filename(
  2016. caption=_("Export FlatCAM Preferences"),
  2017. directory=self.data_path + '/preferences_' + date,
  2018. ext_filter=filter__
  2019. )
  2020. except TypeError:
  2021. filename, _f = FCFileSaveDialog.get_saved_filename(
  2022. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2023. filename = str(filename)
  2024. if filename == "":
  2025. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2026. return
  2027. # Update options
  2028. self.preferencesUiManager.defaults_read_form()
  2029. self.defaults.propagate_defaults()
  2030. # Save update options
  2031. try:
  2032. self.defaults.write(filename=filename)
  2033. except Exception:
  2034. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2035. return
  2036. if self.defaults["global_open_style"] is False:
  2037. self.file_opened.emit("preferences", filename)
  2038. self.file_saved.emit("preferences", filename)
  2039. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2040. def save_to_file(self, content_to_save, txt_content):
  2041. """
  2042. Save something to a file.
  2043. :return: None
  2044. """
  2045. self.defaults.report_usage("save_to_file")
  2046. App.log.debug("save_to_file()")
  2047. self.date = str(datetime.today()).rpartition('.')[0]
  2048. self.date = ''.join(c for c in self.date if c not in ':-')
  2049. self.date = self.date.replace(' ', '_')
  2050. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2051. path_to_save = self.defaults["global_last_save_folder"] if \
  2052. self.defaults["global_last_save_folder"] is not None else self.data_path
  2053. try:
  2054. filename, _f = FCFileSaveDialog.get_saved_filename(
  2055. caption=_("Save to file"),
  2056. directory=path_to_save + '/file_' + self.date,
  2057. ext_filter=filter__
  2058. )
  2059. except TypeError:
  2060. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2061. filename = str(filename)
  2062. if filename == "":
  2063. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2064. return
  2065. else:
  2066. try:
  2067. with open(filename, 'w') as f:
  2068. ___ = f.read()
  2069. except PermissionError:
  2070. self.inform.emit('[WARNING] %s' %
  2071. _("Permission denied, saving not possible.\n"
  2072. "Most likely another app is holding the file open and not accessible."))
  2073. return
  2074. except IOError:
  2075. App.log.debug('Creating a new file ...')
  2076. f = open(filename, 'w')
  2077. f.close()
  2078. except Exception:
  2079. e = sys.exc_info()[0]
  2080. App.log.error("Could not load the file.")
  2081. App.log.error(str(e))
  2082. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2083. return
  2084. # Save content
  2085. if filename.rpartition('.')[2].lower() == 'html':
  2086. file_content = content_to_save
  2087. else:
  2088. file_content = txt_content
  2089. try:
  2090. with open(filename, "w") as f:
  2091. f.write(file_content)
  2092. except Exception:
  2093. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2094. return
  2095. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2096. def register_recent(self, kind, filename):
  2097. """
  2098. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2099. dictionary.
  2100. :param kind: type of file that was opened
  2101. :param filename: the path and file name for the file that was opened
  2102. :return:
  2103. """
  2104. self.log.debug("register_recent()")
  2105. self.log.debug(" %s" % kind)
  2106. self.log.debug(" %s" % filename)
  2107. record = {'kind': str(kind), 'filename': str(filename)}
  2108. if record in self.recent:
  2109. return
  2110. if record in self.recent_projects:
  2111. return
  2112. if record['kind'] == 'project':
  2113. self.recent_projects.insert(0, record)
  2114. else:
  2115. self.recent.insert(0, record)
  2116. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2117. self.recent.pop()
  2118. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2119. self.recent_projects.pop()
  2120. try:
  2121. f = open(self.data_path + '/recent.json', 'w')
  2122. except IOError:
  2123. App.log.error("Failed to open recent items file for writing.")
  2124. self.inform.emit('[ERROR_NOTCL] %s' %
  2125. _('Failed to open recent files file for writing.'))
  2126. return
  2127. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2128. f.close()
  2129. try:
  2130. fp = open(self.data_path + '/recent_projects.json', 'w')
  2131. except IOError:
  2132. App.log.error("Failed to open recent items file for writing.")
  2133. self.inform.emit('[ERROR_NOTCL] %s' %
  2134. _('Failed to open recent projects file for writing.'))
  2135. return
  2136. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2137. fp.close()
  2138. # Re-build the recent items menu
  2139. self.setup_recent_items()
  2140. def on_about(self):
  2141. """
  2142. Displays the "about" dialog found in the Menu --> Help.
  2143. :return: None
  2144. """
  2145. self.defaults.report_usage("on_about")
  2146. version = self.version
  2147. version_date = self.version_date
  2148. beta = self.beta
  2149. class AboutDialog(QtWidgets.QDialog):
  2150. def __init__(self, app, parent=None):
  2151. QtWidgets.QDialog.__init__(self, parent)
  2152. self.app = app
  2153. # Icon and title
  2154. self.setWindowIcon(parent.app_icon)
  2155. self.setWindowTitle(_("About FlatCAM"))
  2156. self.resize(600, 200)
  2157. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2158. # self.setStyleSheet(
  2159. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2160. # "background-attachment: fixed"
  2161. # )
  2162. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2163. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2164. # palette = QtGui.QPalette()
  2165. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2166. # self.setPalette(palette)
  2167. logo = QtWidgets.QLabel()
  2168. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2169. title = QtWidgets.QLabel(
  2170. "<font size=8><B>FlatCAM</B></font><BR>"
  2171. "{title}<BR>"
  2172. "<BR>"
  2173. "<BR>"
  2174. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2175. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2176. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2177. "<B>{issue}</B></a><BR>".format(
  2178. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2179. devel=_("Development"),
  2180. down=_("DOWNLOAD"),
  2181. issue=_("Issue tracker"))
  2182. )
  2183. title.setOpenExternalLinks(True)
  2184. closebtn = QtWidgets.QPushButton(_("Close"))
  2185. tab_widget = QtWidgets.QTabWidget()
  2186. description_label = QtWidgets.QLabel(
  2187. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2188. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2189. version=version,
  2190. beta=('BETA' if beta else ''),
  2191. date=version_date,
  2192. arch=platform.architecture()[0])
  2193. )
  2194. description_label.setOpenExternalLinks(True)
  2195. lic_lbl_header = QtWidgets.QLabel(
  2196. '%s:<br>%s<br>' % (
  2197. _('Licensed under the MIT license'),
  2198. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2199. "http://www.opensource.org/licenses/mit-license.php</a>"
  2200. )
  2201. )
  2202. lic_lbl_header.setOpenExternalLinks(True)
  2203. lic_lbl_body = QtWidgets.QLabel(
  2204. _(
  2205. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2206. 'of this software and associated documentation files (the "Software"), to deal\n'
  2207. 'in the Software without restriction, including without limitation the rights\n'
  2208. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2209. 'copies of the Software, and to permit persons to whom the Software is\n'
  2210. 'furnished to do so, subject to the following conditions:\n\n'
  2211. 'The above copyright notice and this permission notice shall be included in\n'
  2212. 'all copies or substantial portions of the Software.\n\n'
  2213. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2214. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2215. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2216. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2217. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2218. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2219. 'THE SOFTWARE.'
  2220. )
  2221. )
  2222. attributions_label = QtWidgets.QLabel(
  2223. _(
  2224. 'Some of the icons used are from the following sources:<br>'
  2225. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2226. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2227. 'title="Flaticon">www.flaticon.com</a></div>'
  2228. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2229. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2230. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2231. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2232. 'title="Flaticon">www.flaticon.com</a></div>'
  2233. )
  2234. )
  2235. attributions_label.setOpenExternalLinks(True)
  2236. # layouts
  2237. layout1 = QtWidgets.QVBoxLayout()
  2238. layout1_1 = QtWidgets.QHBoxLayout()
  2239. layout1_2 = QtWidgets.QHBoxLayout()
  2240. layout2 = QtWidgets.QHBoxLayout()
  2241. layout3 = QtWidgets.QHBoxLayout()
  2242. self.setLayout(layout1)
  2243. layout1.addLayout(layout1_1)
  2244. layout1.addLayout(layout1_2)
  2245. layout1.addLayout(layout2)
  2246. layout1.addLayout(layout3)
  2247. layout1_1.addStretch()
  2248. layout1_1.addWidget(description_label)
  2249. layout1_2.addWidget(tab_widget)
  2250. self.splash_tab = QtWidgets.QWidget()
  2251. self.splash_tab.setObjectName("splash_about")
  2252. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2253. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2254. tab_widget.addTab(self.splash_tab, _("Splash"))
  2255. self.programmmers_tab = QtWidgets.QWidget()
  2256. self.programmmers_tab.setObjectName("programmers_about")
  2257. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2258. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2259. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2260. self.translators_tab = QtWidgets.QWidget()
  2261. self.translators_tab.setObjectName("translators_about")
  2262. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2263. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2264. tab_widget.addTab(self.translators_tab, _("Translators"))
  2265. self.license_tab = QtWidgets.QWidget()
  2266. self.license_tab.setObjectName("license_about")
  2267. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2268. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2269. tab_widget.addTab(self.license_tab, _("License"))
  2270. self.attributions_tab = QtWidgets.QWidget()
  2271. self.attributions_tab.setObjectName("attributions_about")
  2272. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2273. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2274. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2275. self.splash_tab_layout.addWidget(logo, stretch=0)
  2276. self.splash_tab_layout.addWidget(title, stretch=1)
  2277. pal = QtGui.QPalette()
  2278. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2279. self.prog_grid_lay = QtWidgets.QGridLayout()
  2280. self.prog_grid_lay.setHorizontalSpacing(20)
  2281. self.prog_grid_lay.setColumnStretch(0, 0)
  2282. self.prog_grid_lay.setColumnStretch(2, 1)
  2283. prog_widget = QtWidgets.QWidget()
  2284. prog_widget.setLayout(self.prog_grid_lay)
  2285. prog_scroll = QtWidgets.QScrollArea()
  2286. prog_scroll.setWidget(prog_widget)
  2287. prog_scroll.setWidgetResizable(True)
  2288. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2289. prog_scroll.setPalette(pal)
  2290. self.programmmers_tab_layout.addWidget(prog_scroll)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2338. self.translator_grid_lay = QtWidgets.QGridLayout()
  2339. self.translator_grid_lay.setColumnStretch(0, 0)
  2340. self.translator_grid_lay.setColumnStretch(1, 0)
  2341. self.translator_grid_lay.setColumnStretch(2, 1)
  2342. self.translator_grid_lay.setColumnStretch(3, 0)
  2343. # trans_widget = QtWidgets.QWidget()
  2344. # trans_widget.setLayout(self.translator_grid_lay)
  2345. # self.translators_tab_layout.addWidget(trans_widget)
  2346. # self.translators_tab_layout.addStretch()
  2347. trans_widget = QtWidgets.QWidget()
  2348. trans_widget.setLayout(self.translator_grid_lay)
  2349. trans_scroll = QtWidgets.QScrollArea()
  2350. trans_scroll.setWidget(trans_widget)
  2351. trans_scroll.setWidgetResizable(True)
  2352. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2353. trans_scroll.setPalette(pal)
  2354. self.translators_tab_layout.addWidget(trans_scroll)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2365. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2388. self.translator_grid_lay.setColumnStretch(0, 0)
  2389. self.translators_tab_layout.addStretch()
  2390. self.license_tab_layout.addWidget(lic_lbl_header)
  2391. self.license_tab_layout.addWidget(lic_lbl_body)
  2392. self.license_tab_layout.addStretch()
  2393. self.attributions_tab_layout.addWidget(attributions_label)
  2394. self.attributions_tab_layout.addStretch()
  2395. layout3.addStretch()
  2396. layout3.addWidget(closebtn)
  2397. closebtn.clicked.connect(self.accept)
  2398. AboutDialog(app=self, parent=self.ui).exec_()
  2399. def on_readme(self):
  2400. """
  2401. Displays the "about" dialog found in the Menu --> Help.
  2402. :return: None
  2403. """
  2404. class ReadmeDialog(QtWidgets.QDialog):
  2405. def __init__(self, app, parent=None):
  2406. QtWidgets.QDialog.__init__(self, parent)
  2407. self.app = app
  2408. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2409. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2410. "<b>click</b></a>"
  2411. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2412. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2413. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2414. # Icon and title
  2415. self.setWindowIcon(parent.app_icon)
  2416. self.setWindowTitle(_("Important Information's"))
  2417. self.resize(750, 375)
  2418. logo = QtWidgets.QLabel()
  2419. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2420. content = QtWidgets.QLabel(
  2421. "%s<br>"
  2422. "%s<br><br>"
  2423. "%s,<br>"
  2424. "%s<br>"
  2425. "<ul>"
  2426. "<li> &nbsp;%s %s</li>"
  2427. "<li> &nbsp;%s %s</li>"
  2428. "</ul>"
  2429. "%s %s.<br>"
  2430. "%s"
  2431. "<ul>"
  2432. "<li> &nbsp;%s &#128077;</li>"
  2433. "<li> &nbsp;%s &#128513;</li>"
  2434. "</ul>" %
  2435. (
  2436. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2437. _("Yet it cannot evolve without <b>contributions</b>."),
  2438. _("If you want to see this application grow and become better and better"),
  2439. _("you can <b>contribute</b> to the development yourself by:"),
  2440. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2441. new_features_link,
  2442. _("Bug Reports by providing the steps required to reproduce the bug"),
  2443. bugs_link,
  2444. _("If you like or use this program you can make a donation"),
  2445. donation_link,
  2446. _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2447. _("it will be welcomed with joy"),
  2448. _("it will give me a reason to continue")
  2449. )
  2450. )
  2451. content.setOpenExternalLinks(True)
  2452. # palette
  2453. pal = QtGui.QPalette()
  2454. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2455. # layouts
  2456. main_layout = QtWidgets.QVBoxLayout()
  2457. self.setLayout(main_layout)
  2458. tab_layout = QtWidgets.QHBoxLayout()
  2459. buttons_hlay = QtWidgets.QHBoxLayout()
  2460. main_layout.addLayout(tab_layout)
  2461. main_layout.addLayout(buttons_hlay)
  2462. tab_widget = QtWidgets.QTabWidget()
  2463. tab_layout.addWidget(tab_widget)
  2464. closebtn = QtWidgets.QPushButton(_("Close"))
  2465. buttons_hlay.addStretch()
  2466. buttons_hlay.addWidget(closebtn)
  2467. # CONTRIBUTE section
  2468. self.intro_tab = QtWidgets.QWidget()
  2469. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2470. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2471. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2472. self.grid_lay = QtWidgets.QGridLayout()
  2473. self.grid_lay.setHorizontalSpacing(20)
  2474. self.grid_lay.setColumnStretch(0, 0)
  2475. self.grid_lay.setColumnStretch(1, 1)
  2476. intro_wdg = QtWidgets.QWidget()
  2477. intro_wdg.setLayout(self.grid_lay)
  2478. intro_scroll_area = QtWidgets.QScrollArea()
  2479. intro_scroll_area.setWidget(intro_wdg)
  2480. intro_scroll_area.setWidgetResizable(True)
  2481. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2482. intro_scroll_area.setPalette(pal)
  2483. self.grid_lay.addWidget(logo, 0, 0)
  2484. self.grid_lay.addWidget(content, 0, 1)
  2485. self.intro_tab_layout.addWidget(intro_scroll_area)
  2486. # LINKS EXCHANGE section
  2487. self.links_tab = QtWidgets.QWidget()
  2488. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2489. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2490. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2491. self.links_lay = QtWidgets.QHBoxLayout()
  2492. links_wdg = QtWidgets.QWidget()
  2493. links_wdg.setLayout(self.links_lay)
  2494. links_scroll_area = QtWidgets.QScrollArea()
  2495. links_scroll_area.setWidget(links_wdg)
  2496. links_scroll_area.setWidgetResizable(True)
  2497. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2498. links_scroll_area.setPalette(pal)
  2499. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2500. self.links_tab_layout.addWidget(links_scroll_area)
  2501. # HOW TO section
  2502. self.howto_tab = QtWidgets.QWidget()
  2503. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2504. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2505. tab_widget.addTab(self.howto_tab, _("How To's"))
  2506. self.howto_lay = QtWidgets.QHBoxLayout()
  2507. howto_wdg = QtWidgets.QWidget()
  2508. howto_wdg.setLayout(self.howto_lay)
  2509. howto_scroll_area = QtWidgets.QScrollArea()
  2510. howto_scroll_area.setWidget(howto_wdg)
  2511. howto_scroll_area.setWidgetResizable(True)
  2512. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2513. howto_scroll_area.setPalette(pal)
  2514. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2515. self.howto_tab_layout.addWidget(howto_scroll_area)
  2516. # BUTTONS section
  2517. closebtn.clicked.connect(self.accept)
  2518. ReadmeDialog(app=self, parent=self.ui).exec_()
  2519. def install_bookmarks(self, book_dict=None):
  2520. """
  2521. Install the bookmarks actions in the Help menu -> Bookmarks
  2522. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2523. :return: None
  2524. """
  2525. if book_dict is None:
  2526. self.defaults["global_bookmarks"].update(
  2527. {
  2528. '1': ['FlatCAM', "http://flatcam.org"],
  2529. '2': ['Backup Site', ""]
  2530. }
  2531. )
  2532. else:
  2533. self.defaults["global_bookmarks"].clear()
  2534. self.defaults["global_bookmarks"].update(book_dict)
  2535. # first try to disconnect if somehow they get connected from elsewhere
  2536. for act in self.ui.menuhelp_bookmarks.actions():
  2537. try:
  2538. act.triggered.disconnect()
  2539. except TypeError:
  2540. pass
  2541. # clear all actions except the last one who is the Bookmark manager
  2542. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2543. pass
  2544. else:
  2545. self.ui.menuhelp_bookmarks.removeAction(act)
  2546. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2547. if self.defaults["global_bookmarks"]:
  2548. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2549. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2550. # the JSON is first making the keys as strings (therefore I have to use strings too
  2551. # or do the conversion :(
  2552. # )
  2553. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2554. # the '10' entry jsut after '1' therefore ordering as strings
  2555. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2556. key=lambda x: int(x[0]))
  2557. for entry, bookmark in sorted_bookmarks:
  2558. title = bookmark[0]
  2559. weblink = bookmark[1]
  2560. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2561. act.setText(title)
  2562. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2563. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2564. if title == 'Backup Site' and weblink == "":
  2565. act.triggered.connect(self.on_backup_site)
  2566. else:
  2567. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2568. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2569. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2570. def on_bookmarks_manager(self):
  2571. """
  2572. Adds the bookmark manager in a Tab in Plot Area
  2573. :return:
  2574. """
  2575. for idx in range(self.ui.plot_tab_area.count()):
  2576. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2577. # there can be only one instance of Bookmark Manager at one time
  2578. return
  2579. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2580. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2581. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2582. # add the tab if it was closed
  2583. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2584. # delete the absolute and relative position and messages in the infobar
  2585. self.ui.position_label.setText("")
  2586. # self.ui.rel_position_label.setText("")
  2587. # Switch plot_area to preferences page
  2588. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2589. def on_backup_site(self):
  2590. msgbox = QtWidgets.QMessageBox()
  2591. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2592. "1. FlatCAM.org website is down\n"
  2593. "2. Someone forked FlatCAM project and wants to point\n"
  2594. "to his own website\n\n"
  2595. "If you can't get any informations about FlatCAM beta\n"
  2596. "use the YouTube channel link from the Help menu."))
  2597. msgbox.setWindowTitle(_("Alternative website"))
  2598. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2599. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2600. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2601. msgbox.setDefaultButton(bt_yes)
  2602. msgbox.exec_()
  2603. # response = msgbox.clickedButton()
  2604. def on_file_savedefaults(self):
  2605. """
  2606. Callback for menu item File->Save Defaults. Saves application default options
  2607. ``self.defaults`` to current_defaults.FlatConfig.
  2608. :return: None
  2609. """
  2610. self.preferencesUiManager.save_defaults()
  2611. def final_save(self):
  2612. """
  2613. Callback for doing a preferences save to file whenever the application is about to quit.
  2614. If the project has changes, it will ask the user to save the project.
  2615. :return: None
  2616. """
  2617. if self.save_in_progress:
  2618. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2619. return
  2620. if self.should_we_save and self.collection.get_list():
  2621. msgbox = QtWidgets.QMessageBox()
  2622. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2623. "\n"
  2624. "Do you want to Save the project?"))
  2625. msgbox.setWindowTitle(_("Save changes"))
  2626. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2627. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2628. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2629. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2630. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2631. msgbox.setDefaultButton(bt_yes)
  2632. msgbox.exec_()
  2633. response = msgbox.clickedButton()
  2634. if response == bt_yes:
  2635. try:
  2636. self.trayIcon.hide()
  2637. except Exception:
  2638. pass
  2639. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2640. elif response == bt_no:
  2641. try:
  2642. self.trayIcon.hide()
  2643. except Exception:
  2644. pass
  2645. self.quit_application()
  2646. elif response == bt_cancel:
  2647. return
  2648. else:
  2649. try:
  2650. self.trayIcon.hide()
  2651. except Exception:
  2652. pass
  2653. self.quit_application()
  2654. def quit_application(self):
  2655. """
  2656. Called (as a pyslot or not) when the application is quit.
  2657. :return: None
  2658. """
  2659. # close editors before quiting the app, if they are open
  2660. if self.geo_editor.editor_active is True:
  2661. self.geo_editor.deactivate()
  2662. try:
  2663. self.geo_editor.disconnect()
  2664. except TypeError:
  2665. pass
  2666. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2667. if self.exc_editor.editor_active is True:
  2668. self.exc_editor.deactivate()
  2669. try:
  2670. self.grb_editor.disconnect()
  2671. except TypeError:
  2672. pass
  2673. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2674. if self.grb_editor.editor_active is True:
  2675. self.grb_editor.deactivate_grb_editor()
  2676. try:
  2677. self.exc_editor.disconnect()
  2678. except TypeError:
  2679. pass
  2680. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2681. # disconnect the mouse events
  2682. if self.is_legacy:
  2683. self.plotcanvas.graph_event_disconnect(self.mm)
  2684. self.plotcanvas.graph_event_disconnect(self.mp)
  2685. self.plotcanvas.graph_event_disconnect(self.mr)
  2686. self.plotcanvas.graph_event_disconnect(self.mdc)
  2687. self.plotcanvas.graph_event_disconnect(self.kp)
  2688. else:
  2689. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2690. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2691. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2692. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2693. self.on_mouse_double_click_over_plot)
  2694. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2695. self.preferencesUiManager.save_defaults(silent=True)
  2696. log.debug("App.quit_application() --> App Defaults saved.")
  2697. if self.cmd_line_headless != 1:
  2698. # save app state to file
  2699. stgs = QSettings("Open Source", "FlatCAM")
  2700. stgs.setValue('saved_gui_state', self.ui.saveState())
  2701. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2702. stgs.setValue(
  2703. 'language',
  2704. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2705. )
  2706. stgs.setValue(
  2707. 'notebook_font_size',
  2708. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2709. )
  2710. stgs.setValue(
  2711. 'axis_font_size',
  2712. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2713. )
  2714. stgs.setValue(
  2715. 'textbox_font_size',
  2716. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2717. )
  2718. stgs.setValue(
  2719. 'hud_font_size',
  2720. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2721. )
  2722. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2723. stgs.setValue(
  2724. 'machinist',
  2725. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2726. )
  2727. # This will write the setting to the platform specific storage.
  2728. del stgs
  2729. log.debug("App.quit_application() --> App UI state saved.")
  2730. # try to quit the Socket opened by ArgsThread class
  2731. try:
  2732. self.new_launch.thread_exit = True
  2733. self.new_launch.listener.close()
  2734. self.new_launch.stop.emit()
  2735. except Exception as err:
  2736. log.debug("App.quit_application() --> %s" % str(err))
  2737. # try to quit the QThread that run ArgsThread class
  2738. try:
  2739. del self.new_launch
  2740. self.listen_th.terminate()
  2741. except Exception as e:
  2742. log.debug("App.quit_application() --> %s" % str(e))
  2743. # terminate workers
  2744. self.workers.__del__()
  2745. self.clear_pool()
  2746. # quit app by signalling for self.kill_app() method
  2747. # self.close_app_signal.emit()
  2748. QtWidgets.qApp.quit()
  2749. # QtCore.QCoreApplication.quit()
  2750. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2751. # we use the following command
  2752. minor_v = sys.version_info.minor
  2753. if minor_v < 8:
  2754. # sys.exit(0)
  2755. pass
  2756. else:
  2757. os._exit(0) # fix to work with Python 3.8
  2758. @staticmethod
  2759. def kill_app():
  2760. QtWidgets.qApp.quit()
  2761. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2762. # we use the following command
  2763. sys.exit(0)
  2764. def on_portable_checked(self, state):
  2765. """
  2766. Callback called when the checkbox in Preferences GUI is checked.
  2767. It will set the application as portable by creating the preferences and recent files in the
  2768. 'config' folder found in the FlatCAM installation folder.
  2769. :param state: boolean, the state of the checkbox when clicked/checked
  2770. :return:
  2771. """
  2772. line_no = 0
  2773. data = None
  2774. if sys.platform != 'win32':
  2775. # this won't work in Linux or MacOS
  2776. return
  2777. # test if the app was frozen and choose the path for the configuration file
  2778. if getattr(sys, "frozen", False) is True:
  2779. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2780. else:
  2781. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2782. config_file = current_data_path + '\\configuration.txt'
  2783. try:
  2784. with open(config_file, 'r') as f:
  2785. try:
  2786. data = f.readlines()
  2787. except Exception as e:
  2788. log.debug('App.__init__() -->%s' % str(e))
  2789. return
  2790. except FileNotFoundError:
  2791. pass
  2792. for line in data:
  2793. line = line.strip('\n')
  2794. param = str(line).rpartition('=')
  2795. if param[0] == 'portable':
  2796. break
  2797. line_no += 1
  2798. if state:
  2799. data[line_no] = 'portable=True\n'
  2800. # create the new defauults files
  2801. # create current_defaults.FlatConfig file if there is none
  2802. try:
  2803. f = open(current_data_path + '/current_defaults.FlatConfig')
  2804. f.close()
  2805. except IOError:
  2806. App.log.debug('Creating empty current_defaults.FlatConfig')
  2807. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2808. json.dump({}, f)
  2809. f.close()
  2810. # create factory_defaults.FlatConfig file if there is none
  2811. try:
  2812. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2813. f.close()
  2814. except IOError:
  2815. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2816. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2817. json.dump({}, f)
  2818. f.close()
  2819. try:
  2820. f = open(current_data_path + '/recent.json')
  2821. f.close()
  2822. except IOError:
  2823. App.log.debug('Creating empty recent.json')
  2824. f = open(current_data_path + '/recent.json', 'w')
  2825. json.dump([], f)
  2826. f.close()
  2827. try:
  2828. fp = open(current_data_path + '/recent_projects.json')
  2829. fp.close()
  2830. except IOError:
  2831. App.log.debug('Creating empty recent_projects.json')
  2832. fp = open(current_data_path + '/recent_projects.json', 'w')
  2833. json.dump([], fp)
  2834. fp.close()
  2835. # save the current defaults to the new defaults file
  2836. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2837. else:
  2838. data[line_no] = 'portable=False\n'
  2839. with open(config_file, 'w') as f:
  2840. f.writelines(data)
  2841. def on_register_files(self, obj_type=None):
  2842. """
  2843. Called whenever there is a need to register file extensions with FlatCAM.
  2844. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2845. :param obj_type: the type of object to be register for.
  2846. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2847. :return: None
  2848. """
  2849. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2850. new_reg_path = 'Software\\Classes\\'
  2851. # find if the current user is admin
  2852. try:
  2853. is_admin = os.getuid() == 0
  2854. except AttributeError:
  2855. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2856. if is_admin is True:
  2857. root_path = winreg.HKEY_LOCAL_MACHINE
  2858. else:
  2859. root_path = winreg.HKEY_CURRENT_USER
  2860. # create the keys
  2861. def set_reg(name, root_pth, new_reg_path, value):
  2862. try:
  2863. winreg.CreateKey(root_pth, new_reg_path)
  2864. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2865. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2866. return True
  2867. except WindowsError:
  2868. return False
  2869. # delete key in registry
  2870. def delete_reg(root_pth, reg_path, key_to_del):
  2871. key_to_del_path = reg_path + key_to_del
  2872. try:
  2873. winreg.DeleteKey(root_pth, key_to_del_path)
  2874. return True
  2875. except WindowsError:
  2876. return False
  2877. if obj_type is None or obj_type == 'excellon':
  2878. exc_list = \
  2879. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2880. exc_list = [x for x in exc_list if x != '']
  2881. # register all keys in the Preferences window
  2882. for ext in exc_list:
  2883. new_k = new_reg_path + '.%s' % ext
  2884. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2885. # and unregister those that are no longer in the Preferences windows but are in the file
  2886. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2887. if ext not in exc_list:
  2888. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2889. # now write the updated extensions to the self.defaults
  2890. # new_ext = ''
  2891. # for ext in exc_list:
  2892. # new_ext = new_ext + ext + ', '
  2893. # self.defaults["fa_excellon"] = new_ext
  2894. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2895. if obj_type is None or obj_type == 'gcode':
  2896. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2897. gco_list = [x for x in gco_list if x != '']
  2898. # register all keys in the Preferences window
  2899. for ext in gco_list:
  2900. new_k = new_reg_path + '.%s' % ext
  2901. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2902. # and unregister those that are no longer in the Preferences windows but are in the file
  2903. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2904. if ext not in gco_list:
  2905. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2906. # now write the updated extensions to the self.defaults
  2907. # new_ext = ''
  2908. # for ext in gco_list:
  2909. # new_ext = new_ext + ext + ', '
  2910. # self.defaults["fa_gcode"] = new_ext
  2911. self.inform.emit('[success] %s' %
  2912. _("Selected GCode file extensions registered with FlatCAM."))
  2913. if obj_type is None or obj_type == 'gerber':
  2914. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2915. grb_list = [x for x in grb_list if x != '']
  2916. # register all keys in the Preferences window
  2917. for ext in grb_list:
  2918. new_k = new_reg_path + '.%s' % ext
  2919. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2920. # and unregister those that are no longer in the Preferences windows but are in the file
  2921. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2922. if ext not in grb_list:
  2923. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2924. # now write the updated extensions to the self.defaults
  2925. # new_ext = ''
  2926. # for ext in grb_list:
  2927. # new_ext = new_ext + ext + ', '
  2928. # self.defaults["fa_gerber"] = new_ext
  2929. self.inform.emit('[success] %s' %
  2930. _("Selected Gerber file extensions registered with FlatCAM."))
  2931. def add_extension(self, ext_type):
  2932. """
  2933. Add a file extension to the list for a specific object
  2934. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2935. :return:
  2936. """
  2937. if ext_type == 'excellon':
  2938. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2939. if new_ext == '':
  2940. return
  2941. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2942. if new_ext in old_val:
  2943. return
  2944. old_val.append(new_ext)
  2945. old_val.sort()
  2946. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2947. if ext_type == 'gcode':
  2948. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2949. if new_ext == '':
  2950. return
  2951. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2952. if new_ext in old_val:
  2953. return
  2954. old_val.append(new_ext)
  2955. old_val.sort()
  2956. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2957. if ext_type == 'gerber':
  2958. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2959. if new_ext == '':
  2960. return
  2961. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2962. if new_ext in old_val:
  2963. return
  2964. old_val.append(new_ext)
  2965. old_val.sort()
  2966. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2967. if ext_type == 'keyword':
  2968. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2969. if new_kw == '':
  2970. return
  2971. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2972. if new_kw in old_val:
  2973. return
  2974. old_val.append(new_kw)
  2975. old_val.sort()
  2976. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2977. # update the self.myKeywords so the model is updated
  2978. self.autocomplete_kw_list = \
  2979. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2980. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2981. self.shell._edit.set_model_data(self.myKeywords)
  2982. def del_extension(self, ext_type):
  2983. """
  2984. Remove a file extension from the list for a specific object
  2985. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2986. :return:
  2987. """
  2988. if ext_type == 'excellon':
  2989. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2990. if new_ext == '':
  2991. return
  2992. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2993. if new_ext not in old_val:
  2994. return
  2995. old_val.remove(new_ext)
  2996. old_val.sort()
  2997. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2998. if ext_type == 'gcode':
  2999. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3000. if new_ext == '':
  3001. return
  3002. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3003. if new_ext not in old_val:
  3004. return
  3005. old_val.remove(new_ext)
  3006. old_val.sort()
  3007. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3008. if ext_type == 'gerber':
  3009. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3010. if new_ext == '':
  3011. return
  3012. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3013. if new_ext not in old_val:
  3014. return
  3015. old_val.remove(new_ext)
  3016. old_val.sort()
  3017. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3018. if ext_type == 'keyword':
  3019. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3020. if new_kw == '':
  3021. return
  3022. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3023. if new_kw not in old_val:
  3024. return
  3025. old_val.remove(new_kw)
  3026. old_val.sort()
  3027. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3028. # update the self.myKeywords so the model is updated
  3029. self.autocomplete_kw_list = \
  3030. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3031. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3032. self.shell._edit.set_model_data(self.myKeywords)
  3033. def restore_extensions(self, ext_type):
  3034. """
  3035. Restore all file extensions associations with FlatCAM, for a specific object
  3036. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3037. :return:
  3038. """
  3039. if ext_type == 'excellon':
  3040. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3041. # for the ability to open Excellon files with .txt extension
  3042. new_exc_list = deepcopy(self.exc_list)
  3043. try:
  3044. new_exc_list.remove('txt')
  3045. except ValueError:
  3046. pass
  3047. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3048. if ext_type == 'gcode':
  3049. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3050. if ext_type == 'gerber':
  3051. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3052. if ext_type == 'keyword':
  3053. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3054. # update the self.myKeywords so the model is updated
  3055. self.autocomplete_kw_list = self.default_keywords
  3056. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3057. self.shell._edit.set_model_data(self.myKeywords)
  3058. def delete_all_extensions(self, ext_type):
  3059. """
  3060. Delete all file extensions associations with FlatCAM, for a specific object
  3061. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3062. :return:
  3063. """
  3064. if ext_type == 'excellon':
  3065. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3066. if ext_type == 'gcode':
  3067. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3068. if ext_type == 'gerber':
  3069. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3070. if ext_type == 'keyword':
  3071. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3072. # update the self.myKeywords so the model is updated
  3073. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3074. self.shell._edit.set_model_data(self.myKeywords)
  3075. def on_edit_join(self, name=None):
  3076. """
  3077. Callback for Edit->Join. Joins the selected geometry objects into
  3078. a new one.
  3079. :return: None
  3080. """
  3081. self.defaults.report_usage("on_edit_join()")
  3082. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3083. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3084. geo_type_set = set()
  3085. objs = self.collection.get_selected()
  3086. if len(objs) < 2:
  3087. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3088. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3089. return 'fail'
  3090. for obj in objs:
  3091. geo_type_set.add(obj.multigeo)
  3092. # if len(geo_type_list) == 1 means that all list elements are the same
  3093. if len(geo_type_set) != 1:
  3094. self.inform.emit('[ERROR] %s' %
  3095. _("Failed join. The Geometry objects are of different types.\n"
  3096. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3097. "convert from one to another and retry joining \n"
  3098. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3099. "the result may not be what was expected. \n"
  3100. "Check the generated GCODE."))
  3101. return
  3102. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3103. if True in geo_type_set:
  3104. def initialize(geo_obj, app):
  3105. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3106. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3107. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3108. for v in geo_obj.tools.values():
  3109. v['data']['name'] = obj_name_multi
  3110. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3111. else:
  3112. def initialize(geo_obj, app):
  3113. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3114. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3115. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3116. for v in geo_obj.tools.values():
  3117. v['data']['name'] = obj_name_single
  3118. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3119. self.should_we_save = True
  3120. def on_edit_join_exc(self):
  3121. """
  3122. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3123. a new Excellon.
  3124. :return: None
  3125. """
  3126. self.defaults.report_usage("on_edit_join_exc()")
  3127. objs = self.collection.get_selected()
  3128. for obj in objs:
  3129. if not isinstance(obj, ExcellonObject):
  3130. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3131. return
  3132. if len(objs) < 2:
  3133. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3134. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3135. return 'fail'
  3136. def initialize(exc_obj, app):
  3137. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3138. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3139. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3140. self.should_we_save = True
  3141. def on_edit_join_grb(self):
  3142. """
  3143. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3144. a new Gerber object.
  3145. :return: None
  3146. """
  3147. self.defaults.report_usage("on_edit_join_grb()")
  3148. objs = self.collection.get_selected()
  3149. for obj in objs:
  3150. if not isinstance(obj, GerberObject):
  3151. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3152. return
  3153. if len(objs) < 2:
  3154. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3155. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3156. return 'fail'
  3157. def initialize(grb_obj, app):
  3158. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3159. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3160. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3161. self.should_we_save = True
  3162. def on_convert_singlegeo_to_multigeo(self):
  3163. """
  3164. Called for converting a Geometry object from single-geo to multi-geo.
  3165. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3166. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3167. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3168. the solid-geometry of that tool.
  3169. :return: None
  3170. """
  3171. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3172. obj = self.collection.get_active()
  3173. if obj is None:
  3174. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3175. return
  3176. if not isinstance(obj, GeometryObject):
  3177. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3178. return
  3179. obj.multigeo = True
  3180. for tooluid, dict_value in obj.tools.items():
  3181. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3182. if not isinstance(obj.solid_geometry, list):
  3183. obj.solid_geometry = [obj.solid_geometry]
  3184. # obj.solid_geometry[:] = []
  3185. obj.plot()
  3186. self.should_we_save = True
  3187. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3188. def on_convert_multigeo_to_singlegeo(self):
  3189. """
  3190. Called for converting a Geometry object from multi-geo to single-geo.
  3191. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3192. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3193. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3194. the solid-geometry of that tool.
  3195. :return: None
  3196. """
  3197. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3198. obj = self.collection.get_active()
  3199. if obj is None:
  3200. self.inform.emit('[ERROR_NOTCL] %s' %
  3201. _("Failed. Select a Geometry Object and try again."))
  3202. return
  3203. if not isinstance(obj, GeometryObject):
  3204. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3205. (_("Expected a GeometryObject, got"), type(obj)))
  3206. return
  3207. obj.multigeo = False
  3208. total_solid_geometry = []
  3209. for tooluid, dict_value in obj.tools.items():
  3210. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3211. # clear the original geometry
  3212. dict_value['solid_geometry'][:] = []
  3213. obj.solid_geometry = deepcopy(total_solid_geometry)
  3214. obj.plot()
  3215. self.should_we_save = True
  3216. self.inform.emit('[success] %s' %
  3217. _("A Geometry object was converted to SingleGeo type."))
  3218. def on_defaults_dict_change(self, field):
  3219. """
  3220. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3221. Edit -> Preferences tab window.
  3222. :param field: the key of the self.defaults dictionary that was changed.
  3223. :return: None
  3224. """
  3225. self.preferencesUiManager.defaults_write_form_field(field=field)
  3226. if field == "units":
  3227. self.set_screen_units(self.defaults['units'])
  3228. def set_screen_units(self, units):
  3229. """
  3230. Set the FlatCAM units on the status bar.
  3231. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3232. :return: None
  3233. """
  3234. self.ui.units_label.setText("[" + units.lower() + "]")
  3235. def on_toggle_units_click(self):
  3236. try:
  3237. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3238. except (TypeError, AttributeError):
  3239. pass
  3240. if self.defaults["units"] == 'MM':
  3241. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3242. else:
  3243. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3244. self.on_toggle_units(no_pref=True)
  3245. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3246. lambda: self.on_toggle_units(no_pref=False))
  3247. def on_toggle_units(self, no_pref=False):
  3248. """
  3249. Callback for the Units radio-button change in the Preferences tab.
  3250. Changes the application's default units adn for the project too.
  3251. If changing the project's units, the change propagates to all of
  3252. the objects in the project.
  3253. :return: None
  3254. """
  3255. self.defaults.report_usage("on_toggle_units")
  3256. if self.toggle_units_ignore:
  3257. return
  3258. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3259. # If option is the same, then ignore
  3260. if new_units == self.defaults["units"].upper():
  3261. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3262. return
  3263. # Keys in self.defaults for which to scale their values
  3264. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3265. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3266. "tools_iso_tool_vtipdia",
  3267. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3268. "gerber_editor_ma_high",
  3269. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3270. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3271. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3272. "excellon_feedrate_probe", "excellon_milling_dia",
  3273. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3274. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3275. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3276. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3277. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3278. "geometry_extracut_length", "geometry_z_pdepth",
  3279. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3280. 'cncjob_tooldia',
  3281. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3282. "tools_paintnewdia",
  3283. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3284. "tools_nccnewdia", "tools_ncc_offset_value",
  3285. "tools_2sided_drilldia",
  3286. "tools_film_boundary", "tools_film_scale_stroke",
  3287. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3288. "tools_cutout_depthperpass",
  3289. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3290. "tools_panelize_spacing_rows",
  3291. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3292. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3293. "tools_transform_buffer_dis",
  3294. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3295. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3296. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3297. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3298. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3299. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3300. "tools_cr_h2h_val", "tools_cr_dh_val",
  3301. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3302. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3303. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3304. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3305. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3306. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3307. "tools_copper_thieving_mask_clearance",
  3308. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3309. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3310. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3311. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3312. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3313. "tools_invert_margin",
  3314. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3315. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3316. def scale_defaults(sfactor):
  3317. for dim in dimensions:
  3318. if dim in [
  3319. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3320. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3321. 'tools_transform_mirror_point'
  3322. ]:
  3323. if self.defaults[dim] is None or self.defaults[dim] == '':
  3324. continue
  3325. try:
  3326. coordinates = self.defaults[dim].split(",")
  3327. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3328. coords_xy[0] *= sfactor
  3329. coords_xy[1] *= sfactor
  3330. self.defaults[dim] = "%.*f, %.*f" % (
  3331. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3332. except Exception as e:
  3333. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3334. elif dim in [
  3335. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3336. ]:
  3337. if self.defaults[dim] is None or self.defaults[dim] == '':
  3338. continue
  3339. try:
  3340. self.defaults[dim] = float(self.defaults[dim])
  3341. tools_diameters = [self.defaults[dim]]
  3342. except ValueError:
  3343. try:
  3344. tools_string = self.defaults[dim].split(",")
  3345. tools_diameters = [eval(a) for a in tools_string if a != '']
  3346. except Exception as e:
  3347. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3348. continue
  3349. self.defaults[dim] = ''
  3350. td_len = len(tools_diameters)
  3351. if td_len > 1:
  3352. for t in range(td_len):
  3353. tools_diameters[t] *= sfactor
  3354. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3355. else:
  3356. tools_diameters[0] *= sfactor
  3357. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3358. elif dim in ['global_gridx', 'global_gridy']:
  3359. # format the number of decimals to the one specified in self.decimals
  3360. try:
  3361. val = float(self.defaults[dim]) * sfactor
  3362. except Exception as e:
  3363. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3364. continue
  3365. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3366. else:
  3367. # the number of decimals for the rest is kept unchanged
  3368. if self.defaults[dim]:
  3369. try:
  3370. val = float(self.defaults[dim]) * sfactor
  3371. except Exception as e:
  3372. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3373. continue
  3374. self.defaults[dim] = val
  3375. # The scaling factor depending on choice of units.
  3376. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3377. # Changing project units. Warn user.
  3378. msgbox = QtWidgets.QMessageBox()
  3379. msgbox.setWindowTitle(_("Toggle Units"))
  3380. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3381. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3382. msgbox.setText(_("Changing the units of the project\n"
  3383. "will scale all objects.\n\n"
  3384. "Do you want to continue?"))
  3385. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3386. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3387. msgbox.setDefaultButton(bt_ok)
  3388. msgbox.exec_()
  3389. response = msgbox.clickedButton()
  3390. if response == bt_ok:
  3391. if no_pref is False:
  3392. self.preferencesUiManager.defaults_read_form()
  3393. scale_defaults(factor)
  3394. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3395. self.defaults["units"] = new_units
  3396. # update the defaults from form, some may assume that the conversion is enough and it's not
  3397. self.on_options_app2project()
  3398. # update the objects
  3399. for obj in self.collection.get_list():
  3400. obj.convert_units(new_units)
  3401. # make that the properties stored in the object are also updated
  3402. self.app_obj.object_changed.emit(obj)
  3403. # rebuild the object UI
  3404. obj.build_ui()
  3405. # change this only if the workspace is active
  3406. if self.defaults['global_workspace'] is True:
  3407. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3408. # adjust the grid values on the main toolbar
  3409. val_x = float(self.defaults['global_gridx']) * factor
  3410. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3411. current = self.collection.get_active()
  3412. if current is not None:
  3413. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3414. if not isinstance(current, GeometryObject):
  3415. current.to_form()
  3416. # replot all objects
  3417. self.plot_all()
  3418. # set the status labels to reflect the current FlatCAM units
  3419. self.set_screen_units(new_units)
  3420. # signal to the app that we changed the object properties and it should save the project
  3421. self.should_we_save = True
  3422. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3423. else:
  3424. # Undo toggling
  3425. self.toggle_units_ignore = True
  3426. if self.defaults['units'].upper() == 'MM':
  3427. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3428. else:
  3429. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3430. self.toggle_units_ignore = False
  3431. # store the grid values so they are not changed in the next step
  3432. val_x = float(self.defaults['global_gridx'])
  3433. val_y = float(self.defaults['global_gridy'])
  3434. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3435. self.preferencesUiManager.defaults_read_form()
  3436. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3437. # in self.defaults from the GUI elements but
  3438. # I don't want it for the grid values, so I update them here
  3439. self.defaults['global_gridx'] = val_x
  3440. self.defaults['global_gridy'] = val_y
  3441. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3442. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3443. def on_tab_rmb_click(self, checked):
  3444. self.ui.notebook.set_detachable(val=checked)
  3445. self.defaults["global_tabs_detachable"] = checked
  3446. self.ui.plot_tab_area.set_detachable(val=checked)
  3447. self.defaults["global_tabs_detachable"] = checked
  3448. def on_tab_setup_context_menu(self):
  3449. initial_checked = self.defaults["global_tabs_detachable"]
  3450. action_name = str(_("Detachable Tabs"))
  3451. action = QtWidgets.QAction(self)
  3452. action.setCheckable(True)
  3453. action.setText(action_name)
  3454. action.setChecked(initial_checked)
  3455. self.ui.notebook.tabBar.addAction(action)
  3456. self.ui.plot_tab_area.tabBar.addAction(action)
  3457. try:
  3458. action.triggered.disconnect()
  3459. except TypeError:
  3460. pass
  3461. action.triggered.connect(self.on_tab_rmb_click)
  3462. def on_deselect_all(self):
  3463. self.collection.set_all_inactive()
  3464. self.delete_selection_shape()
  3465. def on_workspace_modified(self):
  3466. # self.save_defaults(silent=True)
  3467. self.plotcanvas.delete_workspace()
  3468. self.preferencesUiManager.defaults_read_form()
  3469. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3470. def on_workspace(self):
  3471. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3472. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3473. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3474. else:
  3475. self.plotcanvas.delete_workspace()
  3476. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3477. self.preferencesUiManager.defaults_read_form()
  3478. # self.save_defaults(silent=True)
  3479. def on_workspace_toggle(self):
  3480. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3481. try:
  3482. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3483. except TypeError:
  3484. pass
  3485. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3486. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3487. self.on_workspace()
  3488. def on_cursor_type(self, val):
  3489. """
  3490. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3491. :return: None
  3492. """
  3493. self.app_cursor.enabled = False
  3494. if val == 'small':
  3495. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3496. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3497. self.app_cursor = self.plotcanvas.new_cursor()
  3498. else:
  3499. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3500. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3501. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3502. if self.ui.grid_snap_btn.isChecked():
  3503. self.app_cursor.enabled = True
  3504. else:
  3505. self.app_cursor.enabled = False
  3506. def on_tool_add_keypress(self):
  3507. # ## Current application units in Upper Case
  3508. self.units = self.defaults['units'].upper()
  3509. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3510. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3511. if notebook_widget_name == 'selected_tab':
  3512. if self.collection.get_active().kind == 'geometry':
  3513. # Tool add works for Geometry only if Advanced is True in Preferences
  3514. if self.defaults["global_app_level"] == 'a':
  3515. tool_add_popup = FCInputDialog(title="New Tool ...",
  3516. text='Enter a Tool Diameter:',
  3517. min=0.0000, max=99.9999, decimals=4)
  3518. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3519. val, ok = tool_add_popup.get_value()
  3520. if ok:
  3521. if float(val) == 0:
  3522. self.inform.emit('[WARNING_NOTCL] %s' %
  3523. _("Please enter a tool diameter with non-zero value, in Float format."))
  3524. return
  3525. self.collection.get_active().on_tool_add(dia=float(val))
  3526. else:
  3527. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3528. else:
  3529. msgbox = QtWidgets.QMessageBox()
  3530. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3531. "Go to Preferences -> General - Show Advanced Options."))
  3532. msgbox.setWindowTitle("Tool adding ...")
  3533. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3534. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3535. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3536. msgbox.setDefaultButton(bt_ok)
  3537. msgbox.exec_()
  3538. # work only if the notebook tab on focus is the Tools_Tab
  3539. if notebook_widget_name == 'tool_tab':
  3540. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3541. # and only if the tool is NCC Tool
  3542. if tool_widget == self.ncclear_tool.toolName:
  3543. self.ncclear_tool.on_add_tool_by_key()
  3544. # and only if the tool is Paint Area Tool
  3545. elif tool_widget == self.paint_tool.toolName:
  3546. self.paint_tool.on_add_tool_by_key()
  3547. # and only if the tool is Solder Paste Dispensing Tool
  3548. elif tool_widget == self.paste_tool.toolName:
  3549. self.paste_tool.on_add_tool_by_key()
  3550. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3551. # See description below.
  3552. def on_delete_keypress(self):
  3553. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3554. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3555. if notebook_widget_name == 'selected_tab':
  3556. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3557. self.collection.get_active().on_tool_delete()
  3558. # work only if the notebook tab on focus is the Tools_Tab
  3559. elif notebook_widget_name == 'tool_tab':
  3560. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3561. # and only if the tool is NCC Tool
  3562. if tool_widget == self.ncclear_tool.toolName:
  3563. self.ncclear_tool.on_tool_delete()
  3564. # and only if the tool is Paint Tool
  3565. elif tool_widget == self.paint_tool.toolName:
  3566. self.paint_tool.on_tool_delete()
  3567. # and only if the tool is Solder Paste Dispensing Tool
  3568. elif tool_widget == self.paste_tool.toolName:
  3569. self.paste_tool.on_tool_delete()
  3570. # and only if the tool is Isolation Tool
  3571. elif tool_widget == self.isolation_tool.toolName:
  3572. self.isolation_tool.on_tool_delete()
  3573. else:
  3574. self.on_delete()
  3575. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3576. # some screens you have to be careful where you hover with your mouse.
  3577. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3578. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3579. # Complicated, I know :)
  3580. def on_delete(self, force_deletion=False):
  3581. """
  3582. Delete the currently selected FlatCAMObjs.
  3583. :param force_deletion: used by Tcl command
  3584. :return: None
  3585. """
  3586. self.defaults.report_usage("on_delete()")
  3587. response = None
  3588. bt_ok = None
  3589. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3590. # a geometry object before we update it.
  3591. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3592. and self.grb_editor.editor_active is False:
  3593. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3594. msgbox = QtWidgets.QMessageBox()
  3595. msgbox.setWindowTitle(_("Delete objects"))
  3596. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3597. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3598. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3599. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3600. "the selected objects?"))
  3601. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3602. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3603. msgbox.setDefaultButton(bt_ok)
  3604. msgbox.exec_()
  3605. response = msgbox.clickedButton()
  3606. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3607. response = bt_ok
  3608. if response == bt_ok:
  3609. if self.collection.get_active():
  3610. self.log.debug("App.on_delete()")
  3611. for obj_active in self.collection.get_selected():
  3612. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3613. if obj_active.kind == 'gerber':
  3614. for el in obj_active.mark_shapes:
  3615. obj_active.mark_shapes[el].clear(update=True)
  3616. obj_active.mark_shapes[el].enabled = False
  3617. # obj_active.mark_shapes[el] = None
  3618. del el
  3619. elif obj_active.kind == 'cncjob':
  3620. try:
  3621. obj_active.text_col.enabled = False
  3622. del obj_active.text_col
  3623. obj_active.annotation.clear(update=True)
  3624. del obj_active.annotation
  3625. except AttributeError as e:
  3626. log.debug(
  3627. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3628. )
  3629. while self.collection.get_selected():
  3630. self.delete_first_selected()
  3631. # make sure that the selection shape is deleted, too
  3632. self.delete_selection_shape()
  3633. # if there are no longer objects delete also the exclusion areas shapes
  3634. if not self.collection.get_list():
  3635. self.exc_areas.clear_shapes()
  3636. self.inform.emit('%s...' % _("Object(s) deleted"))
  3637. else:
  3638. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3639. else:
  3640. self.inform.emit(_("Save the work in Editor and try again ..."))
  3641. def delete_first_selected(self):
  3642. # Keep this for later
  3643. try:
  3644. sel_obj = self.collection.get_active()
  3645. name = sel_obj.options["name"]
  3646. isPlotted = sel_obj.options["plot"]
  3647. except AttributeError:
  3648. self.log.debug("Nothing selected for deletion")
  3649. return
  3650. if self.is_legacy is True:
  3651. # Remove plot only if the object was plotted otherwise delaxes will fail
  3652. if isPlotted:
  3653. try:
  3654. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3655. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3656. except Exception as e:
  3657. log.debug("App.delete_first_selected() --> %s" % str(e))
  3658. self.plotcanvas.auto_adjust_axes()
  3659. # Remove from dictionary
  3660. self.collection.delete_active()
  3661. # Clear form
  3662. self.setup_component_editor()
  3663. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3664. def on_set_origin(self):
  3665. """
  3666. Set the origin to the left mouse click position
  3667. :return: None
  3668. """
  3669. # display the message for the user
  3670. # and ask him to click on the desired position
  3671. self.defaults.report_usage("on_set_origin()")
  3672. def origin_replot():
  3673. def worker_task():
  3674. with self.proc_container.new('%s...' % _("Plotting")):
  3675. for obj in self.collection.get_list():
  3676. obj.plot()
  3677. self.plotcanvas.fit_view()
  3678. if self.is_legacy:
  3679. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3680. else:
  3681. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3682. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3683. self.inform.emit(_('Click to set the origin ...'))
  3684. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3685. # first disconnect it as it may have been used by something else
  3686. try:
  3687. self.replot_signal.disconnect()
  3688. except TypeError:
  3689. pass
  3690. self.replot_signal[list].connect(origin_replot)
  3691. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3692. """
  3693. :param event:
  3694. :param location:
  3695. :param noplot:
  3696. :param use_thread:
  3697. :return:
  3698. """
  3699. noplot_sig = noplot
  3700. def worker_task():
  3701. with self.proc_container.new(_("Setting Origin...")):
  3702. obj_list = self.collection.get_list()
  3703. for obj in obj_list:
  3704. obj.offset((x, y))
  3705. self.app_obj.object_changed.emit(obj)
  3706. # Update the object bounding box options
  3707. a, b, c, d = obj.bounds()
  3708. obj.options['xmin'] = a
  3709. obj.options['ymin'] = b
  3710. obj.options['xmax'] = c
  3711. obj.options['ymax'] = d
  3712. self.inform.emit('[success] %s...' % _('Origin set'))
  3713. for obj in obj_list:
  3714. out_name = obj.options["name"]
  3715. if obj.kind == 'gerber':
  3716. obj.source_file = self.export_gerber(
  3717. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3718. elif obj.kind == 'excellon':
  3719. obj.source_file = self.export_excellon(
  3720. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3721. if noplot_sig is False:
  3722. self.replot_signal.emit([])
  3723. if location is not None:
  3724. if len(location) != 2:
  3725. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3726. return 'fail'
  3727. x, y = location
  3728. if use_thread is True:
  3729. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3730. else:
  3731. worker_task()
  3732. self.should_we_save = True
  3733. return
  3734. if event is not None and event.button == 1:
  3735. if self.is_legacy is False:
  3736. event_pos = event.pos
  3737. else:
  3738. event_pos = (event.xdata, event.ydata)
  3739. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3740. if self.grid_status():
  3741. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3742. else:
  3743. pos = pos_canvas
  3744. x = 0 - pos[0]
  3745. y = 0 - pos[1]
  3746. if use_thread is True:
  3747. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3748. else:
  3749. worker_task()
  3750. self.should_we_save = True
  3751. def on_move2origin(self, use_thread=True):
  3752. """
  3753. Move selected objects to origin.
  3754. :param use_thread: Control if to use threaded operation. Boolean.
  3755. :return:
  3756. """
  3757. def worker_task():
  3758. with self.proc_container.new(_("Moving to Origin...")):
  3759. obj_list = self.collection.get_selected()
  3760. if not obj_list:
  3761. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3762. return
  3763. xminlist = []
  3764. yminlist = []
  3765. # first get a bounding box to fit all
  3766. for obj in obj_list:
  3767. xmin, ymin, xmax, ymax = obj.bounds()
  3768. xminlist.append(xmin)
  3769. yminlist.append(ymin)
  3770. # get the minimum x,y for all objects selected
  3771. x = min(xminlist)
  3772. y = min(yminlist)
  3773. for obj in obj_list:
  3774. obj.offset((-x, -y))
  3775. self.app_obj.object_changed.emit(obj)
  3776. # Update the object bounding box options
  3777. a, b, c, d = obj.bounds()
  3778. obj.options['xmin'] = a
  3779. obj.options['ymin'] = b
  3780. obj.options['xmax'] = c
  3781. obj.options['ymax'] = d
  3782. for obj in obj_list:
  3783. obj.plot()
  3784. for obj in obj_list:
  3785. out_name = obj.options["name"]
  3786. if obj.kind == 'gerber':
  3787. obj.source_file = self.export_gerber(
  3788. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3789. elif obj.kind == 'excellon':
  3790. obj.source_file = self.export_excellon(
  3791. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3792. self.inform.emit('[success] %s...' % _('Origin set'))
  3793. if use_thread is True:
  3794. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3795. else:
  3796. worker_task()
  3797. self.should_we_save = True
  3798. def on_jump_to(self, custom_location=None, fit_center=True):
  3799. """
  3800. Jump to a location by setting the mouse cursor location.
  3801. :param custom_location: Jump to a specified point. (x, y) tuple.
  3802. :param fit_center: If to fit view. Boolean.
  3803. :return:
  3804. """
  3805. self.defaults.report_usage("on_jump_to()")
  3806. if not custom_location:
  3807. dia_box_location = None
  3808. try:
  3809. dia_box_location = eval(self.clipboard.text())
  3810. except Exception:
  3811. pass
  3812. if type(dia_box_location) == tuple:
  3813. dia_box_location = str(dia_box_location)
  3814. else:
  3815. dia_box_location = None
  3816. # dia_box = Dialog_box(title=_("Jump to ..."),
  3817. # label=_("Enter the coordinates in format X,Y:"),
  3818. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3819. # initial_text=dia_box_location)
  3820. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3821. label=_("Enter the coordinates in format X,Y:"),
  3822. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3823. initial_text=dia_box_location,
  3824. reference=self.defaults['global_jump_ref'])
  3825. if dia_box.ok is True:
  3826. try:
  3827. location = eval(dia_box.location)
  3828. if not isinstance(location, tuple):
  3829. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3830. return
  3831. if dia_box.reference == 'rel':
  3832. rel_x = self.mouse[0] + location[0]
  3833. rel_y = self.mouse[1] + location[1]
  3834. location = (rel_x, rel_y)
  3835. self.defaults['global_jump_ref'] = dia_box.reference
  3836. except Exception:
  3837. return
  3838. else:
  3839. return
  3840. else:
  3841. location = custom_location
  3842. self.jump_signal.emit(location)
  3843. if fit_center:
  3844. self.plotcanvas.fit_center(loc=location)
  3845. cursor = QtGui.QCursor()
  3846. if self.is_legacy is False:
  3847. # I don't know where those differences come from but they are constant for the current
  3848. # execution of the application and they are multiples of a value around 0.0263mm.
  3849. # In a random way sometimes they are more sometimes they are less
  3850. # if units == 'MM':
  3851. # cal_factor = 0.0263
  3852. # else:
  3853. # cal_factor = 0.0263 / 25.4
  3854. cal_location = (location[0], location[1])
  3855. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3856. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3857. j_pos = (
  3858. int(canvas_origin.x() + round(jump_loc[0])),
  3859. int(canvas_origin.y() + round(jump_loc[1]))
  3860. )
  3861. cursor.setPos(j_pos[0], j_pos[1])
  3862. else:
  3863. # find the canvas origin which is in the top left corner
  3864. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3865. # determine the coordinates for the lowest left point of the canvas
  3866. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3867. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3868. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3869. # canvas) and the point (width, height) is in the top-right location
  3870. loc = self.plotcanvas.axes.transData.transform_point(location)
  3871. j_pos = (
  3872. int(x0 + loc[0]),
  3873. int(y0 - loc[1])
  3874. )
  3875. cursor.setPos(j_pos[0], j_pos[1])
  3876. self.plotcanvas.mouse = [location[0], location[1]]
  3877. if self.defaults["global_cursor_color_enabled"] is True:
  3878. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3879. else:
  3880. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3881. if self.grid_status():
  3882. # Update cursor
  3883. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3884. symbol='++', edge_color=self.cursor_color_3D,
  3885. edge_width=self.defaults["global_cursor_width"],
  3886. size=self.defaults["global_cursor_size"])
  3887. # Set the relative position label
  3888. dx = location[0] - float(self.rel_point1[0])
  3889. dy = location[1] - float(self.rel_point1[1])
  3890. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3891. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3892. # # Set the position label
  3893. #
  3894. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3895. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3896. units = self.defaults["units"].lower()
  3897. self.plotcanvas.text_hud.text = \
  3898. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3899. dx, units, dy, units, location[0], units, location[1], units)
  3900. self.inform.emit('[success] %s' % _("Done."))
  3901. return location
  3902. def on_locate(self, obj, fit_center=True):
  3903. """
  3904. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3905. :param obj: The object on which to locate certain points
  3906. :param fit_center: If to fit view. Boolean.
  3907. :return: A point location. (x, y) tuple.
  3908. """
  3909. self.defaults.report_usage("on_locate()")
  3910. if obj is None:
  3911. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3912. return 'fail'
  3913. class DialogBoxChoice(QtWidgets.QDialog):
  3914. def __init__(self, title=None, icon=None, choice='bl'):
  3915. """
  3916. :param title: string with the window title
  3917. """
  3918. super(DialogBoxChoice, self).__init__()
  3919. self.ok = False
  3920. self.setWindowIcon(icon)
  3921. self.setWindowTitle(str(title))
  3922. self.form = QtWidgets.QFormLayout(self)
  3923. self.ref_radio = RadioSet([
  3924. {"label": _("Bottom-Left"), "value": "bl"},
  3925. {"label": _("Top-Left"), "value": "tl"},
  3926. {"label": _("Bottom-Right"), "value": "br"},
  3927. {"label": _("Top-Right"), "value": "tr"},
  3928. {"label": _("Center"), "value": "c"}
  3929. ], orientation='vertical', stretch=False)
  3930. self.ref_radio.set_value(choice)
  3931. self.form.addRow(self.ref_radio)
  3932. self.button_box = QtWidgets.QDialogButtonBox(
  3933. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3934. Qt.Horizontal, parent=self)
  3935. self.form.addRow(self.button_box)
  3936. self.button_box.accepted.connect(self.accept)
  3937. self.button_box.rejected.connect(self.reject)
  3938. if self.exec_() == QtWidgets.QDialog.Accepted:
  3939. self.ok = True
  3940. self.location_point = self.ref_radio.get_value()
  3941. else:
  3942. self.ok = False
  3943. self.location_point = None
  3944. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3945. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3946. choice=self.defaults['global_locate_pt'])
  3947. if dia_box.ok is True:
  3948. try:
  3949. location_point = dia_box.location_point
  3950. self.defaults['global_locate_pt'] = dia_box.location_point
  3951. except Exception:
  3952. return
  3953. else:
  3954. return
  3955. loc_b = obj.bounds()
  3956. if location_point == 'bl':
  3957. location = (loc_b[0], loc_b[1])
  3958. elif location_point == 'tl':
  3959. location = (loc_b[0], loc_b[3])
  3960. elif location_point == 'br':
  3961. location = (loc_b[2], loc_b[1])
  3962. elif location_point == 'tr':
  3963. location = (loc_b[2], loc_b[3])
  3964. else:
  3965. # center
  3966. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3967. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3968. location = (cx, cy)
  3969. self.locate_signal.emit(location, location_point)
  3970. if fit_center:
  3971. self.plotcanvas.fit_center(loc=location)
  3972. cursor = QtGui.QCursor()
  3973. if self.is_legacy is False:
  3974. # I don't know where those differences come from but they are constant for the current
  3975. # execution of the application and they are multiples of a value around 0.0263mm.
  3976. # In a random way sometimes they are more sometimes they are less
  3977. # if units == 'MM':
  3978. # cal_factor = 0.0263
  3979. # else:
  3980. # cal_factor = 0.0263 / 25.4
  3981. cal_location = (location[0], location[1])
  3982. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3983. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3984. j_pos = (
  3985. int(canvas_origin.x() + round(jump_loc[0])),
  3986. int(canvas_origin.y() + round(jump_loc[1]))
  3987. )
  3988. cursor.setPos(j_pos[0], j_pos[1])
  3989. else:
  3990. # find the canvas origin which is in the top left corner
  3991. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3992. # determine the coordinates for the lowest left point of the canvas
  3993. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3994. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3995. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3996. # canvas) and the point (width, height) is in the top-right location
  3997. loc = self.plotcanvas.axes.transData.transform_point(location)
  3998. j_pos = (
  3999. int(x0 + loc[0]),
  4000. int(y0 - loc[1])
  4001. )
  4002. cursor.setPos(j_pos[0], j_pos[1])
  4003. self.plotcanvas.mouse = [location[0], location[1]]
  4004. if self.defaults["global_cursor_color_enabled"] is True:
  4005. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4006. else:
  4007. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4008. if self.grid_status():
  4009. # Update cursor
  4010. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4011. symbol='++', edge_color=self.cursor_color_3D,
  4012. edge_width=self.defaults["global_cursor_width"],
  4013. size=self.defaults["global_cursor_size"])
  4014. # Set the relative position label
  4015. self.dx = location[0] - float(self.rel_point1[0])
  4016. self.dy = location[1] - float(self.rel_point1[1])
  4017. # Set the position label
  4018. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4019. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4020. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4021. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4022. units = self.defaults["units"].lower()
  4023. self.plotcanvas.text_hud.text = \
  4024. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4025. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4026. self.inform.emit('[success] %s' % _("Done."))
  4027. return location
  4028. def on_copy_command(self):
  4029. """
  4030. Will copy a selection of objects, creating new objects.
  4031. :return:
  4032. """
  4033. self.defaults.report_usage("on_copy_command()")
  4034. def initialize(obj_init, app):
  4035. """
  4036. :param obj_init: the new object
  4037. :type obj_init: class
  4038. :param app: An instance of the App class
  4039. :type app: App
  4040. :return: None
  4041. :rtype:
  4042. """
  4043. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4044. try:
  4045. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4046. except AttributeError:
  4047. pass
  4048. try:
  4049. obj_init.apertures = deepcopy(obj.apertures)
  4050. except AttributeError:
  4051. pass
  4052. try:
  4053. if obj.tools:
  4054. obj_init.tools = deepcopy(obj.tools)
  4055. except Exception as err:
  4056. log.debug("App.on_copy_command() --> %s" % str(err))
  4057. try:
  4058. obj_init.source_file = deepcopy(obj.source_file)
  4059. except (AttributeError, TypeError):
  4060. pass
  4061. def initialize_excellon(obj_init, app):
  4062. obj_init.source_file = deepcopy(obj.source_file)
  4063. obj_init.tools = deepcopy(obj.tools)
  4064. # drills are offset, so they need to be deep copied
  4065. obj_init.drills = deepcopy(obj.drills)
  4066. # slots are offset, so they need to be deep copied
  4067. obj_init.slots = deepcopy(obj.slots)
  4068. obj_init.create_geometry()
  4069. def initialize_script(obj_init, app_obj):
  4070. obj_init.source_file = deepcopy(obj.source_file)
  4071. def initialize_document(obj_init, app_obj):
  4072. obj_init.source_file = deepcopy(obj.source_file)
  4073. for obj in self.collection.get_selected():
  4074. obj_name = obj.options["name"]
  4075. try:
  4076. if isinstance(obj, ExcellonObject):
  4077. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4078. elif isinstance(obj, GerberObject):
  4079. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4080. elif isinstance(obj, GeometryObject):
  4081. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4082. elif isinstance(obj, ScriptObject):
  4083. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4084. elif isinstance(obj, DocumentObject):
  4085. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4086. except Exception as e:
  4087. return "Operation failed: %s" % str(e)
  4088. def on_copy_object2(self, custom_name):
  4089. def initialize_geometry(obj_init, app):
  4090. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4091. try:
  4092. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4093. except AttributeError:
  4094. pass
  4095. try:
  4096. obj_init.apertures = deepcopy(obj.apertures)
  4097. except AttributeError:
  4098. pass
  4099. try:
  4100. if obj.tools:
  4101. obj_init.tools = deepcopy(obj.tools)
  4102. except Exception as ee:
  4103. log.debug("on_copy_object2() --> %s" % str(ee))
  4104. def initialize_gerber(obj_init, app):
  4105. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4106. obj_init.apertures = deepcopy(obj.apertures)
  4107. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4108. def initialize_excellon(obj_init, app):
  4109. obj_init.tools = deepcopy(obj.tools)
  4110. # drills are offset, so they need to be deep copied
  4111. obj_init.drills = deepcopy(obj.drills)
  4112. # slots are offset, so they need to be deep copied
  4113. obj_init.slots = deepcopy(obj.slots)
  4114. obj_init.create_geometry()
  4115. for obj in self.collection.get_selected():
  4116. obj_name = obj.options["name"]
  4117. try:
  4118. if isinstance(obj, ExcellonObject):
  4119. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4120. elif isinstance(obj, GerberObject):
  4121. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4122. elif isinstance(obj, GeometryObject):
  4123. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4124. except Exception as er:
  4125. return "Operation failed: %s" % str(er)
  4126. def on_rename_object(self, text):
  4127. """
  4128. Will rename an object.
  4129. :param text: New name for the object.
  4130. :return:
  4131. """
  4132. self.defaults.report_usage("on_rename_object()")
  4133. named_obj = self.collection.get_active()
  4134. for obj in named_obj:
  4135. if obj is list:
  4136. self.on_rename_object(text)
  4137. else:
  4138. try:
  4139. obj.options['name'] = text
  4140. except Exception as e:
  4141. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4142. def convert_any2geo(self):
  4143. """
  4144. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4145. :return:
  4146. """
  4147. self.defaults.report_usage("convert_any2geo()")
  4148. def initialize(obj_init, app):
  4149. obj_init.solid_geometry = obj.solid_geometry
  4150. try:
  4151. obj_init.follow_geometry = obj.follow_geometry
  4152. except AttributeError:
  4153. pass
  4154. try:
  4155. obj_init.apertures = obj.apertures
  4156. except AttributeError:
  4157. pass
  4158. try:
  4159. if obj.tools:
  4160. obj_init.tools = obj.tools
  4161. except AttributeError:
  4162. pass
  4163. def initialize_excellon(obj_init, app):
  4164. # objs = self.collection.get_selected()
  4165. # GeometryObject.merge(objs, obj)
  4166. solid_geo = []
  4167. for tool in obj.tools:
  4168. for geo in obj.tools[tool]['solid_geometry']:
  4169. solid_geo.append(geo)
  4170. obj_init.solid_geometry = deepcopy(solid_geo)
  4171. if not self.collection.get_selected():
  4172. log.warning("App.convert_any2geo --> No object selected")
  4173. self.inform.emit('[WARNING_NOTCL] %s' %
  4174. _("No object is selected. Select an object and try again."))
  4175. return
  4176. for obj in self.collection.get_selected():
  4177. obj_name = obj.options["name"]
  4178. try:
  4179. if isinstance(obj, ExcellonObject):
  4180. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4181. else:
  4182. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4183. except Exception as e:
  4184. return "Operation failed: %s" % str(e)
  4185. def convert_any2gerber(self):
  4186. """
  4187. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4188. :return:
  4189. """
  4190. self.defaults.report_usage("convert_any2gerber()")
  4191. def initialize_geometry(obj_init, app):
  4192. apertures = {}
  4193. apid = 0
  4194. apertures[str(apid)] = {}
  4195. apertures[str(apid)]['geometry'] = []
  4196. for obj_orig in obj.solid_geometry:
  4197. new_elem = {}
  4198. new_elem['solid'] = obj_orig
  4199. try:
  4200. new_elem['follow'] = obj_orig.exterior
  4201. except AttributeError:
  4202. pass
  4203. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4204. apertures[str(apid)]['size'] = 0.0
  4205. apertures[str(apid)]['type'] = 'C'
  4206. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4207. obj_init.apertures = deepcopy(apertures)
  4208. def initialize_excellon(obj_init, app):
  4209. apertures = {}
  4210. apid = 10
  4211. for tool in obj.tools:
  4212. apertures[str(apid)] = {}
  4213. apertures[str(apid)]['geometry'] = []
  4214. for geo in obj.tools[tool]['solid_geometry']:
  4215. new_el = {}
  4216. new_el['solid'] = geo
  4217. new_el['follow'] = geo.exterior
  4218. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4219. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4220. apertures[str(apid)]['type'] = 'C'
  4221. apid += 1
  4222. # create solid_geometry
  4223. solid_geometry = []
  4224. for apid in apertures:
  4225. for geo_el in apertures[apid]['geometry']:
  4226. solid_geometry.append(geo_el['solid'])
  4227. solid_geometry = MultiPolygon(solid_geometry)
  4228. solid_geometry = solid_geometry.buffer(0.0000001)
  4229. obj_init.solid_geometry = deepcopy(solid_geometry)
  4230. obj_init.apertures = deepcopy(apertures)
  4231. # clear the working objects (perhaps not necessary due of Python GC)
  4232. apertures.clear()
  4233. if not self.collection.get_selected():
  4234. log.warning("App.convert_any2gerber --> No object selected")
  4235. self.inform.emit('[WARNING_NOTCL] %s' %
  4236. _("No object is selected. Select an object and try again."))
  4237. return
  4238. for obj in self.collection.get_selected():
  4239. obj_name = obj.options["name"]
  4240. try:
  4241. if isinstance(obj, ExcellonObject):
  4242. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4243. elif isinstance(obj, GeometryObject):
  4244. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4245. else:
  4246. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4247. except Exception as e:
  4248. return "Operation failed: %s" % str(e)
  4249. def abort_all_tasks(self):
  4250. """
  4251. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4252. on the first possible occasion.
  4253. :return:
  4254. """
  4255. if self.abort_flag is False:
  4256. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4257. self.abort_flag = True
  4258. self.cleanup.emit()
  4259. def app_is_idle(self):
  4260. if self.abort_flag:
  4261. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4262. self.abort_flag = False
  4263. def on_selectall(self):
  4264. """
  4265. Will draw a selection box shape around the selected objects.
  4266. :return:
  4267. """
  4268. self.defaults.report_usage("on_selectall()")
  4269. # delete the possible selection box around a possible selected object
  4270. self.delete_selection_shape()
  4271. for name in self.collection.get_names():
  4272. self.collection.set_active(name)
  4273. curr_sel_obj = self.collection.get_by_name(name)
  4274. # create the selection box around the selected object
  4275. if self.defaults['global_selection_shape'] is True:
  4276. self.draw_selection_shape(curr_sel_obj)
  4277. def on_toggle_preferences(self):
  4278. pref_open = False
  4279. for idx in range(self.ui.plot_tab_area.count()):
  4280. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4281. pref_open = True
  4282. if pref_open:
  4283. for idx in range(self.ui.plot_tab_area.count()):
  4284. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4285. self.ui.plot_tab_area.removeTab(idx)
  4286. break
  4287. self.ui.pref_status_label.setStyleSheet("")
  4288. else:
  4289. self.on_preferences()
  4290. def on_preferences(self):
  4291. """
  4292. Adds the Preferences in a Tab in Plot Area
  4293. :return:
  4294. """
  4295. # add the tab if it was closed
  4296. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4297. # delete the absolute and relative position and messages in the infobar
  4298. self.ui.position_label.setText("")
  4299. # self.ui.rel_position_label.setText("")
  4300. # Switch plot_area to preferences page
  4301. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4302. # self.ui.show()
  4303. self.ui.pref_status_label.setStyleSheet("""
  4304. QLabel
  4305. {
  4306. color: black;
  4307. background-color: lightseagreen;
  4308. }
  4309. """
  4310. )
  4311. # detect changes in the preferences
  4312. for idx in range(self.ui.pref_tab_area.count()):
  4313. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4314. try:
  4315. try:
  4316. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4317. except (TypeError, AttributeError):
  4318. pass
  4319. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4320. except AttributeError:
  4321. pass
  4322. try:
  4323. try:
  4324. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4325. except (TypeError, AttributeError):
  4326. pass
  4327. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4328. except AttributeError:
  4329. pass
  4330. try:
  4331. try:
  4332. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4333. except (TypeError, AttributeError):
  4334. pass
  4335. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4336. except AttributeError:
  4337. pass
  4338. try:
  4339. try:
  4340. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4341. except (TypeError, AttributeError):
  4342. pass
  4343. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4344. except AttributeError:
  4345. pass
  4346. try:
  4347. try:
  4348. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4349. except (TypeError, AttributeError):
  4350. pass
  4351. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4352. except AttributeError:
  4353. pass
  4354. def on_tools_database(self, source='app'):
  4355. """
  4356. Adds the Tools Database in a Tab in Plot Area.
  4357. :return:
  4358. """
  4359. for idx in range(self.ui.plot_tab_area.count()):
  4360. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4361. # there can be only one instance of Tools Database at one time
  4362. return
  4363. if source == 'app':
  4364. self.tools_db_tab = ToolsDB2(
  4365. app=self,
  4366. parent=self.ui,
  4367. callback_on_edited=self.on_tools_db_edited,
  4368. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4369. )
  4370. elif source == 'ncc':
  4371. self.tools_db_tab = ToolsDB2(
  4372. app=self,
  4373. parent=self.ui,
  4374. callback_on_edited=self.on_tools_db_edited,
  4375. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4376. )
  4377. elif source == 'paint':
  4378. self.tools_db_tab = ToolsDB2(
  4379. app=self,
  4380. parent=self.ui,
  4381. callback_on_edited=self.on_tools_db_edited,
  4382. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4383. )
  4384. elif source == 'iso':
  4385. self.tools_db_tab = ToolsDB2(
  4386. app=self,
  4387. parent=self.ui,
  4388. callback_on_edited=self.on_tools_db_edited,
  4389. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4390. )
  4391. # add the tab if it was closed
  4392. try:
  4393. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4394. self.tools_db_tab.setObjectName("database_tab")
  4395. except Exception as e:
  4396. log.debug("App.on_tools_database() --> %s" % str(e))
  4397. return
  4398. # delete the absolute and relative position and messages in the infobar
  4399. self.ui.position_label.setText("")
  4400. # self.ui.rel_position_label.setText("")
  4401. # Switch plot_area to preferences page
  4402. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4403. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4404. self.tools_db_tab.ui_connect()
  4405. def on_tools_db_edited(self):
  4406. """
  4407. Executed whenever a tool is edited in Tools Database.
  4408. Will color the text of the Tools Database tab to Red color.
  4409. :return:
  4410. """
  4411. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4412. for idx in range(self.ui.plot_tab_area.count()):
  4413. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4414. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4415. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4416. self.tools_db_changed_flag = True
  4417. def on_geometry_tool_add_from_db_executed(self, tool):
  4418. """
  4419. Here add the tool from DB in the selected geometry object.
  4420. :return:
  4421. """
  4422. tool_from_db = deepcopy(tool)
  4423. obj = self.collection.get_active()
  4424. if obj.kind == 'geometry':
  4425. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4426. # close the tab and delete it
  4427. for idx in range(self.ui.plot_tab_area.count()):
  4428. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4429. wdg = self.ui.plot_tab_area.widget(idx)
  4430. wdg.deleteLater()
  4431. self.ui.plot_tab_area.removeTab(idx)
  4432. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4433. elif obj.kind == 'gerber':
  4434. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4435. # close the tab and delete it
  4436. for idx in range(self.ui.plot_tab_area.count()):
  4437. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4438. wdg = self.ui.plot_tab_area.widget(idx)
  4439. wdg.deleteLater()
  4440. self.ui.plot_tab_area.removeTab(idx)
  4441. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4442. else:
  4443. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4444. def on_plot_area_tab_closed(self, tab_obj_name):
  4445. """
  4446. Executed whenever a QTab is closed in the Plot Area.
  4447. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4448. :return:
  4449. """
  4450. if tab_obj_name == "preferences_tab":
  4451. self.preferencesUiManager.on_close_preferences_tab()
  4452. elif tab_obj_name == "database_tab":
  4453. # disconnect the signals from the table widget in tab
  4454. self.tools_db_tab.ui_disconnect()
  4455. if self.tools_db_changed_flag is True:
  4456. msgbox = QtWidgets.QMessageBox()
  4457. msgbox.setText(_("One or more Tools are edited.\n"
  4458. "Do you want to update the Tools Database?"))
  4459. msgbox.setWindowTitle(_("Save Tools Database"))
  4460. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4461. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4462. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4463. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4464. msgbox.setDefaultButton(bt_yes)
  4465. msgbox.exec_()
  4466. response = msgbox.clickedButton()
  4467. if response == bt_yes:
  4468. self.tools_db_tab.on_save_tools_db()
  4469. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4470. else:
  4471. self.tools_db_changed_flag = False
  4472. self.inform.emit('')
  4473. return
  4474. self.tools_db_tab.deleteLater()
  4475. elif tab_obj_name == "text_editor_tab":
  4476. self.toggle_codeeditor = False
  4477. elif tab_obj_name == "bookmarks_tab":
  4478. self.book_dialog_tab.rebuild_actions()
  4479. self.book_dialog_tab.deleteLater()
  4480. else:
  4481. return
  4482. # def on_plotarea_tab_closed(self, tab_idx):
  4483. # """
  4484. #
  4485. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4486. # :return:
  4487. # """
  4488. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4489. #
  4490. # if widget is not None:
  4491. # widget.deleteLater()
  4492. # self.ui.plot_tab_area.removeTab(tab_idx)
  4493. def on_flipy(self):
  4494. """
  4495. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4496. :return:
  4497. """
  4498. self.defaults.report_usage("on_flipy()")
  4499. obj_list = self.collection.get_selected()
  4500. xminlist = []
  4501. yminlist = []
  4502. xmaxlist = []
  4503. ymaxlist = []
  4504. if not obj_list:
  4505. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4506. else:
  4507. try:
  4508. # first get a bounding box to fit all
  4509. for obj in obj_list:
  4510. xmin, ymin, xmax, ymax = obj.bounds()
  4511. xminlist.append(xmin)
  4512. yminlist.append(ymin)
  4513. xmaxlist.append(xmax)
  4514. ymaxlist.append(ymax)
  4515. # get the minimum x,y and maximum x,y for all objects selected
  4516. xminimal = min(xminlist)
  4517. yminimal = min(yminlist)
  4518. xmaximal = max(xmaxlist)
  4519. ymaximal = max(ymaxlist)
  4520. px = 0.5 * (xminimal + xmaximal)
  4521. py = 0.5 * (yminimal + ymaximal)
  4522. # execute mirroring
  4523. for obj in obj_list:
  4524. obj.mirror('X', [px, py])
  4525. obj.plot()
  4526. self.app_obj.object_changed.emit(obj)
  4527. self.inform.emit('[success] %s' %
  4528. _("Flip on Y axis done."))
  4529. except Exception as e:
  4530. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4531. return
  4532. def on_flipx(self):
  4533. """
  4534. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4535. :return:
  4536. """
  4537. self.defaults.report_usage("on_flipx()")
  4538. obj_list = self.collection.get_selected()
  4539. xminlist = []
  4540. yminlist = []
  4541. xmaxlist = []
  4542. ymaxlist = []
  4543. if not obj_list:
  4544. self.inform.emit('[WARNING_NOTCL] %s' %
  4545. _("No object selected to Flip on X axis."))
  4546. else:
  4547. try:
  4548. # first get a bounding box to fit all
  4549. for obj in obj_list:
  4550. xmin, ymin, xmax, ymax = obj.bounds()
  4551. xminlist.append(xmin)
  4552. yminlist.append(ymin)
  4553. xmaxlist.append(xmax)
  4554. ymaxlist.append(ymax)
  4555. # get the minimum x,y and maximum x,y for all objects selected
  4556. xminimal = min(xminlist)
  4557. yminimal = min(yminlist)
  4558. xmaximal = max(xmaxlist)
  4559. ymaximal = max(ymaxlist)
  4560. px = 0.5 * (xminimal + xmaximal)
  4561. py = 0.5 * (yminimal + ymaximal)
  4562. # execute mirroring
  4563. for obj in obj_list:
  4564. obj.mirror('Y', [px, py])
  4565. obj.plot()
  4566. self.app_obj.object_changed.emit(obj)
  4567. self.inform.emit('[success] %s' %
  4568. _("Flip on X axis done."))
  4569. except Exception as e:
  4570. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4571. return
  4572. def on_rotate(self, silent=False, preset=None):
  4573. """
  4574. Executed when Options -> Rotate Selection menu entry is clicked.
  4575. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4576. :param preset: A value to be used as predefined angle for rotation.
  4577. :return:
  4578. """
  4579. self.defaults.report_usage("on_rotate()")
  4580. obj_list = self.collection.get_selected()
  4581. xminlist = []
  4582. yminlist = []
  4583. xmaxlist = []
  4584. ymaxlist = []
  4585. if not obj_list:
  4586. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4587. else:
  4588. if silent is False:
  4589. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4590. min=-360, max=360, decimals=4,
  4591. init_val=float(self.defaults['tools_transform_rotate']))
  4592. num, ok = rotatebox.get_value()
  4593. else:
  4594. num = preset
  4595. ok = True
  4596. if ok:
  4597. try:
  4598. # first get a bounding box to fit all
  4599. for obj in obj_list:
  4600. xmin, ymin, xmax, ymax = obj.bounds()
  4601. xminlist.append(xmin)
  4602. yminlist.append(ymin)
  4603. xmaxlist.append(xmax)
  4604. ymaxlist.append(ymax)
  4605. # get the minimum x,y and maximum x,y for all objects selected
  4606. xminimal = min(xminlist)
  4607. yminimal = min(yminlist)
  4608. xmaximal = max(xmaxlist)
  4609. ymaximal = max(ymaxlist)
  4610. px = 0.5 * (xminimal + xmaximal)
  4611. py = 0.5 * (yminimal + ymaximal)
  4612. for sel_obj in obj_list:
  4613. sel_obj.rotate(-float(num), point=(px, py))
  4614. sel_obj.plot()
  4615. self.app_obj.object_changed.emit(sel_obj)
  4616. self.inform.emit('[success] %s' % _("Rotation done."))
  4617. except Exception as e:
  4618. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4619. return
  4620. def on_skewx(self):
  4621. """
  4622. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4623. :return:
  4624. """
  4625. self.defaults.report_usage("on_skewx()")
  4626. obj_list = self.collection.get_selected()
  4627. xminlist = []
  4628. yminlist = []
  4629. if not obj_list:
  4630. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4631. else:
  4632. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4633. min=-360, max=360, decimals=4,
  4634. init_val=float(self.defaults['tools_transform_skew_x']))
  4635. num, ok = skewxbox.get_value()
  4636. if ok:
  4637. # first get a bounding box to fit all
  4638. for obj in obj_list:
  4639. xmin, ymin, xmax, ymax = obj.bounds()
  4640. xminlist.append(xmin)
  4641. yminlist.append(ymin)
  4642. # get the minimum x,y and maximum x,y for all objects selected
  4643. xminimal = min(xminlist)
  4644. yminimal = min(yminlist)
  4645. for obj in obj_list:
  4646. obj.skew(num, 0, point=(xminimal, yminimal))
  4647. obj.plot()
  4648. self.app_obj.object_changed.emit(obj)
  4649. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4650. def on_skewy(self):
  4651. """
  4652. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4653. :return:
  4654. """
  4655. self.defaults.report_usage("on_skewy()")
  4656. obj_list = self.collection.get_selected()
  4657. xminlist = []
  4658. yminlist = []
  4659. if not obj_list:
  4660. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4661. else:
  4662. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4663. min=-360, max=360, decimals=4,
  4664. init_val=float(self.defaults['tools_transform_skew_y']))
  4665. num, ok = skewybox.get_value()
  4666. if ok:
  4667. # first get a bounding box to fit all
  4668. for obj in obj_list:
  4669. xmin, ymin, xmax, ymax = obj.bounds()
  4670. xminlist.append(xmin)
  4671. yminlist.append(ymin)
  4672. # get the minimum x,y and maximum x,y for all objects selected
  4673. xminimal = min(xminlist)
  4674. yminimal = min(yminlist)
  4675. for obj in obj_list:
  4676. obj.skew(0, num, point=(xminimal, yminimal))
  4677. obj.plot()
  4678. self.app_obj.object_changed.emit(obj)
  4679. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4680. def on_plots_updated(self):
  4681. """
  4682. Callback used to report when the plots have changed.
  4683. Adjust axes and zooms to fit.
  4684. :return: None
  4685. """
  4686. if self.is_legacy is False:
  4687. self.plotcanvas.update()
  4688. else:
  4689. self.plotcanvas.auto_adjust_axes()
  4690. self.on_zoom_fit()
  4691. self.collection.update_view()
  4692. # self.inform.emit(_("Plots updated ..."))
  4693. def on_toolbar_replot(self):
  4694. """
  4695. Callback for toolbar button. Re-plots all objects.
  4696. :return: None
  4697. """
  4698. self.log.debug("on_toolbar_replot()")
  4699. try:
  4700. self.collection.get_active().read_form()
  4701. except AttributeError:
  4702. self.log.debug("on_toolbar_replot(): AttributeError")
  4703. pass
  4704. self.plot_all()
  4705. def grid_status(self):
  4706. return True if self.ui.grid_snap_btn.isChecked() else False
  4707. def populate_cmenu_grids(self):
  4708. units = self.defaults['units'].lower()
  4709. # for act in self.ui.cmenu_gridmenu.actions():
  4710. # act.triggered.disconnect()
  4711. self.ui.cmenu_gridmenu.clear()
  4712. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4713. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4714. _("Grid On/Off"))
  4715. grid_toggle.setCheckable(True)
  4716. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4717. self.ui.cmenu_gridmenu.addSeparator()
  4718. for grid in sorted_list:
  4719. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4720. "%s" % str(grid))
  4721. action.triggered.connect(self.set_grid)
  4722. self.ui.cmenu_gridmenu.addSeparator()
  4723. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4724. _("Add"))
  4725. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4726. _("Delete"))
  4727. grid_add.triggered.connect(self.on_grid_add)
  4728. grid_delete.triggered.connect(self.on_grid_delete)
  4729. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4730. def set_grid(self):
  4731. menu_action = self.sender()
  4732. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4733. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4734. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4735. def on_grid_add(self):
  4736. # ## Current application units in lower Case
  4737. units = self.defaults['units'].lower()
  4738. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4739. text=_('Enter a Grid Value:'),
  4740. min=0.0000, max=99.9999, decimals=4)
  4741. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4742. val, ok = grid_add_popup.get_value()
  4743. if ok:
  4744. if float(val) == 0:
  4745. self.inform.emit('[WARNING_NOTCL] %s' %
  4746. _("Please enter a grid value with non-zero value, in Float format."))
  4747. return
  4748. else:
  4749. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4750. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4751. self.inform.emit('[success] %s...' % _("New Grid added"))
  4752. else:
  4753. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4754. else:
  4755. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4756. def on_grid_delete(self):
  4757. # ## Current application units in lower Case
  4758. units = self.defaults['units'].lower()
  4759. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4760. text='Enter a Grid Value:',
  4761. min=0.0000, max=99.9999, decimals=4)
  4762. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4763. val, ok = grid_del_popup.get_value()
  4764. if ok:
  4765. if float(val) == 0:
  4766. self.inform.emit('[WARNING_NOTCL] %s' %
  4767. _("Please enter a grid value with non-zero value, in Float format."))
  4768. return
  4769. else:
  4770. try:
  4771. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4772. except ValueError:
  4773. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4774. return
  4775. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4776. else:
  4777. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4778. def on_shortcut_list(self):
  4779. self.defaults.report_usage("on_shortcut_list()")
  4780. # add the tab if it was closed
  4781. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4782. # delete the absolute and relative position and messages in the infobar
  4783. self.ui.position_label.setText("")
  4784. # self.ui.rel_position_label.setText("")
  4785. # Switch plot_area to preferences page
  4786. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4787. # self.ui.show()
  4788. def on_select_tab(self, name):
  4789. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4790. if self.ui.splitter.sizes()[0] == 0:
  4791. self.ui.splitter.setSizes([1, 1])
  4792. else:
  4793. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4794. self.ui.splitter.setSizes([0, 1])
  4795. if name == 'project':
  4796. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4797. elif name == 'selected':
  4798. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4799. elif name == 'tool':
  4800. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4801. def on_copy_name(self):
  4802. self.defaults.report_usage("on_copy_name()")
  4803. obj = self.collection.get_active()
  4804. try:
  4805. name = obj.options["name"]
  4806. except AttributeError:
  4807. log.debug("on_copy_name() --> No object selected to copy it's name")
  4808. self.inform.emit('[WARNING_NOTCL] %s' %
  4809. _(" No object selected to copy it's name"))
  4810. return
  4811. self.clipboard.setText(name)
  4812. self.inform.emit(_("Name copied on clipboard ..."))
  4813. def on_mouse_click_over_plot(self, event):
  4814. """
  4815. Default actions are:
  4816. :param event: Contains information about the event, like which button
  4817. was clicked, the pixel coordinates and the axes coordinates.
  4818. :return: None
  4819. """
  4820. self.pos = []
  4821. if self.is_legacy is False:
  4822. event_pos = event.pos
  4823. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4824. # # Set the mouse button for panning
  4825. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4826. else:
  4827. event_pos = (event.xdata, event.ydata)
  4828. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4829. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4830. # So it can receive key presses
  4831. self.plotcanvas.native.setFocus()
  4832. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4833. if self.grid_status():
  4834. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4835. else:
  4836. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4837. try:
  4838. if event.button == 1:
  4839. # Reset here the relative coordinates so there is a new reference on the click position
  4840. if self.rel_point1 is None:
  4841. self.rel_point1 = self.pos
  4842. else:
  4843. self.rel_point2 = copy(self.rel_point1)
  4844. self.rel_point1 = self.pos
  4845. self.on_mouse_move_over_plot(event, origin_click=True)
  4846. except Exception as e:
  4847. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4848. def on_mouse_double_click_over_plot(self, event):
  4849. if event.button == 1:
  4850. self.doubleclick = True
  4851. def on_mouse_move_over_plot(self, event, origin_click=None):
  4852. """
  4853. Callback for the mouse motion event over the plot.
  4854. :param event: Contains information about the event.
  4855. :param origin_click
  4856. :return: None
  4857. """
  4858. if self.is_legacy is False:
  4859. event_pos = event.pos
  4860. if self.defaults["global_pan_button"] == '2':
  4861. pan_button = 2
  4862. else:
  4863. pan_button = 3
  4864. self.event_is_dragging = event.is_dragging
  4865. else:
  4866. event_pos = (event.xdata, event.ydata)
  4867. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4868. if self.defaults["global_pan_button"] == '2':
  4869. pan_button = 3
  4870. else:
  4871. pan_button = 2
  4872. self.event_is_dragging = self.plotcanvas.is_dragging
  4873. # So it can receive key presses but not when the Tcl Shell is active
  4874. if not self.ui.shell_dock.isVisible():
  4875. if not self.plotcanvas.native.hasFocus():
  4876. self.plotcanvas.native.setFocus()
  4877. self.pos_jump = event_pos
  4878. self.ui.popMenu.mouse_is_panning = False
  4879. if origin_click is None:
  4880. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4881. if event.button == pan_button and self.event_is_dragging == 1:
  4882. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4883. if self.ui.popMenu.popup_active:
  4884. self.ui.popMenu.popup_active = False
  4885. return
  4886. self.ui.popMenu.mouse_is_panning = True
  4887. return
  4888. if self.rel_point1 is not None:
  4889. try: # May fail in case mouse not within axes
  4890. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4891. if pos_canvas[0] is None or pos_canvas[1] is None:
  4892. return
  4893. if self.grid_status():
  4894. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4895. # Update cursor
  4896. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4897. symbol='++', edge_color=self.cursor_color_3D,
  4898. edge_width=self.defaults["global_cursor_width"],
  4899. size=self.defaults["global_cursor_size"])
  4900. else:
  4901. pos = (pos_canvas[0], pos_canvas[1])
  4902. self.dx = pos[0] - float(self.rel_point1[0])
  4903. self.dy = pos[1] - float(self.rel_point1[1])
  4904. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4905. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4906. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4907. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4908. units = self.defaults["units"].lower()
  4909. self.plotcanvas.text_hud.text = \
  4910. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4911. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4912. self.mouse = [pos[0], pos[1]]
  4913. # if the mouse is moved and the LMB is clicked then the action is a selection
  4914. if self.event_is_dragging == 1 and event.button == 1:
  4915. self.delete_selection_shape()
  4916. if self.dx < 0:
  4917. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4918. face_color=self.defaults['global_alt_sel_fill'])
  4919. self.selection_type = False
  4920. elif self.dx >= 0:
  4921. self.draw_moving_selection_shape(self.pos, pos)
  4922. self.selection_type = True
  4923. else:
  4924. self.selection_type = None
  4925. else:
  4926. self.selection_type = None
  4927. # hover effect - enabled in Preferences -> General -> appGUI Settings
  4928. if self.defaults['global_hover']:
  4929. for obj in self.collection.get_list():
  4930. try:
  4931. # select the object(s) only if it is enabled (plotted)
  4932. if obj.options['plot']:
  4933. if obj not in self.collection.get_selected():
  4934. poly_obj = Polygon(
  4935. [(obj.options['xmin'], obj.options['ymin']),
  4936. (obj.options['xmax'], obj.options['ymin']),
  4937. (obj.options['xmax'], obj.options['ymax']),
  4938. (obj.options['xmin'], obj.options['ymax'])]
  4939. )
  4940. if Point(pos).within(poly_obj):
  4941. if obj.isHovering is False:
  4942. obj.isHovering = True
  4943. obj.notHovering = True
  4944. # create the selection box around the selected object
  4945. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4946. else:
  4947. if obj.notHovering is True:
  4948. obj.notHovering = False
  4949. obj.isHovering = False
  4950. self.delete_hover_shape()
  4951. except Exception:
  4952. # the Exception here will happen if we try to select on screen and we have an
  4953. # newly (and empty) just created Geometry or Excellon object that do not have the
  4954. # xmin, xmax, ymin, ymax options.
  4955. # In this case poly_obj creation (see above) will fail
  4956. pass
  4957. except Exception as e:
  4958. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4959. self.ui.position_label.setText("")
  4960. # self.ui.rel_position_label.setText("")
  4961. self.mouse = None
  4962. def on_mouse_click_release_over_plot(self, event):
  4963. """
  4964. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4965. and has been registered in ''self.__init__()''.
  4966. :param event: contains information about the event.
  4967. :return:
  4968. """
  4969. if self.is_legacy is False:
  4970. event_pos = event.pos
  4971. right_button = 2
  4972. else:
  4973. event_pos = (event.xdata, event.ydata)
  4974. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4975. right_button = 3
  4976. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4977. if self.grid_status():
  4978. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4979. else:
  4980. pos = (pos_canvas[0], pos_canvas[1])
  4981. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4982. # canvas menu
  4983. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4984. self.ui.popMenu.mouse_is_panning = False
  4985. self.cursor = QtGui.QCursor()
  4986. self.populate_cmenu_grids()
  4987. self.ui.popMenu.popup(self.cursor.pos())
  4988. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4989. # selection and then select a type of selection ("enclosing" or "touching")
  4990. if event.button == 1: # left click
  4991. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4992. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4993. if modifiers == QtCore.Qt.ShiftModifier:
  4994. # do not auto open the Project Tab
  4995. self.click_noproject = True
  4996. self.clipboard.setText(
  4997. self.defaults["global_point_clipboard_format"] %
  4998. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4999. )
  5000. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5001. return
  5002. if self.doubleclick is True:
  5003. self.doubleclick = False
  5004. if self.collection.get_selected():
  5005. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5006. if self.ui.splitter.sizes()[0] == 0:
  5007. self.ui.splitter.setSizes([1, 1])
  5008. try:
  5009. # delete the selection shape(S) as it may be in the way
  5010. self.delete_selection_shape()
  5011. self.delete_hover_shape()
  5012. except Exception as e:
  5013. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5014. return
  5015. else:
  5016. # WORKAROUND for LEGACY MODE
  5017. if self.is_legacy is True:
  5018. # if there is no move on canvas then we have no dragging selection
  5019. if self.dx == 0 or self.dy == 0:
  5020. self.selection_type = None
  5021. if self.selection_type is not None:
  5022. try:
  5023. self.selection_area_handler(self.pos, pos, self.selection_type)
  5024. self.selection_type = None
  5025. except Exception as e:
  5026. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5027. return
  5028. else:
  5029. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5030. if key_modifier == QtCore.Qt.ShiftModifier:
  5031. mod_key = 'Shift'
  5032. elif key_modifier == QtCore.Qt.ControlModifier:
  5033. mod_key = 'Control'
  5034. else:
  5035. mod_key = None
  5036. try:
  5037. if self.command_active is None:
  5038. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5039. # deselect, and if it's not selected then it will be selected
  5040. # If there is no active command (self.command_active is None) then we check if we clicked
  5041. # on a object by checking the bounding limits against mouse click position
  5042. if mod_key == self.defaults["global_mselect_key"]:
  5043. self.select_objects(key='multisel')
  5044. else:
  5045. # If there is no active command (self.command_active is None) then we check if
  5046. # we clicked on a object by checking the bounding limits against mouse click position
  5047. self.select_objects()
  5048. self.delete_hover_shape()
  5049. except Exception as e:
  5050. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5051. return
  5052. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5053. """
  5054. :param start_pos: mouse position when the selection LMB click was done
  5055. :param end_pos: mouse position when the left mouse button is released
  5056. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5057. :return:
  5058. """
  5059. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5060. # delete previous selection shape
  5061. self.delete_selection_shape()
  5062. # make all objects inactive
  5063. self.collection.set_all_inactive()
  5064. for obj in self.collection.get_list():
  5065. try:
  5066. # select the object(s) only if it is enabled (plotted)
  5067. if obj.options['plot']:
  5068. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5069. (obj.options['xmax'], obj.options['ymin']),
  5070. (obj.options['xmax'], obj.options['ymax']),
  5071. (obj.options['xmin'], obj.options['ymax'])])
  5072. if sel_type is True:
  5073. if poly_obj.within(poly_selection):
  5074. # create the selection box around the selected object
  5075. if self.defaults['global_selection_shape'] is True:
  5076. self.draw_selection_shape(obj)
  5077. self.collection.set_active(obj.options['name'])
  5078. else:
  5079. if poly_selection.intersects(poly_obj):
  5080. # create the selection box around the selected object
  5081. if self.defaults['global_selection_shape'] is True:
  5082. self.draw_selection_shape(obj)
  5083. self.collection.set_active(obj.options['name'])
  5084. obj.selection_shape_drawn = True
  5085. except Exception as e:
  5086. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5087. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5088. # In this case poly_obj creation (see above) will fail
  5089. log.debug("App.selection_area_handler() --> %s" % str(e))
  5090. def select_objects(self, key=None):
  5091. """
  5092. Will select objects clicked on canvas
  5093. :param key: for future use in cumulative selection
  5094. :return:
  5095. """
  5096. # list where we store the overlapped objects under our mouse left click position
  5097. if key is None:
  5098. self.objects_under_the_click_list = []
  5099. # Populate the list with the overlapped objects on the click position
  5100. curr_x, curr_y = self.pos
  5101. for obj in self.all_objects_list:
  5102. # ScriptObject and DocumentObject objects can't be selected
  5103. if obj.kind == 'script' or obj.kind == 'document':
  5104. continue
  5105. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5106. continue
  5107. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5108. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5109. if obj.options['name'] not in self.objects_under_the_click_list:
  5110. if obj.options['plot']:
  5111. # add objects to the objects_under_the_click list only if the object is plotted
  5112. # (active and not disabled)
  5113. self.objects_under_the_click_list.append(obj.options['name'])
  5114. try:
  5115. if self.objects_under_the_click_list:
  5116. curr_sel_obj = self.collection.get_active()
  5117. # case when there is only an object under the click and we toggle it
  5118. if len(self.objects_under_the_click_list) == 1:
  5119. if curr_sel_obj is None:
  5120. self.collection.set_active(self.objects_under_the_click_list[0])
  5121. curr_sel_obj = self.collection.get_active()
  5122. # create the selection box around the selected object
  5123. if self.defaults['global_selection_shape'] is True:
  5124. self.draw_selection_shape(curr_sel_obj)
  5125. curr_sel_obj.selection_shape_drawn = True
  5126. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5127. self.collection.on_objects_selection(False)
  5128. self.delete_selection_shape()
  5129. curr_sel_obj.selection_shape_drawn = False
  5130. self.collection.set_active(self.objects_under_the_click_list[0])
  5131. curr_sel_obj = self.collection.get_active()
  5132. # create the selection box around the selected object
  5133. if self.defaults['global_selection_shape'] is True:
  5134. self.draw_selection_shape(curr_sel_obj)
  5135. curr_sel_obj.selection_shape_drawn = True
  5136. self.selected_message(curr_sel_obj=curr_sel_obj)
  5137. elif curr_sel_obj.selection_shape_drawn is False:
  5138. if self.defaults['global_selection_shape'] is True:
  5139. self.draw_selection_shape(curr_sel_obj)
  5140. curr_sel_obj.selection_shape_drawn = True
  5141. else:
  5142. self.collection.on_objects_selection(False)
  5143. self.delete_selection_shape()
  5144. if self.call_source != 'app':
  5145. self.call_source = 'app'
  5146. self.selected_message(curr_sel_obj=curr_sel_obj)
  5147. else:
  5148. # If there is no selected object
  5149. # make active the first element of the overlapped objects list
  5150. if self.collection.get_active() is None:
  5151. self.collection.set_active(self.objects_under_the_click_list[0])
  5152. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5153. name_sel_obj = self.collection.get_active().options['name']
  5154. # In case that there is a selected object but it is not in the overlapped object list
  5155. # make that object inactive and activate the first element in the overlapped object list
  5156. if name_sel_obj not in self.objects_under_the_click_list:
  5157. self.collection.set_inactive(name_sel_obj)
  5158. name_sel_obj = self.objects_under_the_click_list[0]
  5159. self.collection.set_active(name_sel_obj)
  5160. else:
  5161. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5162. self.collection.set_all_inactive()
  5163. self.collection.set_active(
  5164. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5165. curr_sel_obj = self.collection.get_active()
  5166. # delete the possible selection box around a possible selected object
  5167. self.delete_selection_shape()
  5168. curr_sel_obj.selection_shape_drawn = False
  5169. # create the selection box around the selected object
  5170. if self.defaults['global_selection_shape'] is True:
  5171. self.draw_selection_shape(curr_sel_obj)
  5172. curr_sel_obj.selection_shape_drawn = True
  5173. self.selected_message(curr_sel_obj=curr_sel_obj)
  5174. else:
  5175. # deselect everything
  5176. self.collection.on_objects_selection(False)
  5177. # delete the possible selection box around a possible selected object
  5178. self.delete_selection_shape()
  5179. for o in self.collection.get_list():
  5180. o.selection_shape_drawn = False
  5181. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5182. # only when working on App
  5183. if self.call_source == 'app':
  5184. if self.click_noproject is False:
  5185. # if the Tool Tab is in focus don't change focus to Project Tab
  5186. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5187. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5188. else:
  5189. # restore auto open the Project Tab
  5190. self.click_noproject = False
  5191. # delete any text in the status bar, implicitly the last object name that was selected
  5192. # self.inform.emit("")
  5193. else:
  5194. self.call_source = 'app'
  5195. except Exception as e:
  5196. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5197. def selected_message(self, curr_sel_obj):
  5198. if curr_sel_obj:
  5199. if curr_sel_obj.kind == 'gerber':
  5200. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5201. color='green',
  5202. name=str(curr_sel_obj.options['name']),
  5203. tx=_("selected"))
  5204. )
  5205. elif curr_sel_obj.kind == 'excellon':
  5206. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5207. color='brown',
  5208. name=str(curr_sel_obj.options['name']),
  5209. tx=_("selected"))
  5210. )
  5211. elif curr_sel_obj.kind == 'cncjob':
  5212. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5213. color='blue',
  5214. name=str(curr_sel_obj.options['name']),
  5215. tx=_("selected"))
  5216. )
  5217. elif curr_sel_obj.kind == 'geometry':
  5218. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5219. color='red',
  5220. name=str(curr_sel_obj.options['name']),
  5221. tx=_("selected"))
  5222. )
  5223. def delete_hover_shape(self):
  5224. self.hover_shapes.clear()
  5225. self.hover_shapes.redraw()
  5226. def draw_hover_shape(self, sel_obj, color=None):
  5227. """
  5228. :param sel_obj: The object for which the hover shape must be drawn
  5229. :param color: The color of the hover shape
  5230. :return: None
  5231. """
  5232. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5233. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5234. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5235. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5236. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5237. if self.defaults['units'].upper() == 'MM':
  5238. hover_rect = hover_rect.buffer(-0.1)
  5239. hover_rect = hover_rect.buffer(0.2)
  5240. else:
  5241. hover_rect = hover_rect.buffer(-0.00393)
  5242. hover_rect = hover_rect.buffer(0.00787)
  5243. # if color:
  5244. # face = Color(color)
  5245. # face.alpha = 0.2
  5246. # outline = Color(color, alpha=0.8)
  5247. # else:
  5248. # face = Color(self.defaults['global_sel_fill'])
  5249. # face.alpha = 0.2
  5250. # outline = self.defaults['global_sel_line']
  5251. if color:
  5252. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5253. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5254. else:
  5255. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5256. outline = self.defaults['global_sel_line']
  5257. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5258. if self.is_legacy is True:
  5259. self.hover_shapes.redraw()
  5260. def delete_selection_shape(self):
  5261. self.move_tool.sel_shapes.clear()
  5262. self.move_tool.sel_shapes.redraw()
  5263. def draw_selection_shape(self, sel_obj, color=None):
  5264. """
  5265. Will draw a selection shape around the selected object.
  5266. :param sel_obj: The object for which the selection shape must be drawn
  5267. :param color: The color for the selection shape.
  5268. :return: None
  5269. """
  5270. if sel_obj is None:
  5271. return
  5272. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5273. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5274. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5275. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5276. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5277. if self.defaults['units'].upper() == 'MM':
  5278. sel_rect = sel_rect.buffer(-0.1)
  5279. sel_rect = sel_rect.buffer(0.2)
  5280. else:
  5281. sel_rect = sel_rect.buffer(-0.00393)
  5282. sel_rect = sel_rect.buffer(0.00787)
  5283. if color:
  5284. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5285. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5286. else:
  5287. if self.is_legacy is False:
  5288. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5289. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5290. else:
  5291. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5292. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5293. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5294. color=outline,
  5295. face_color=face,
  5296. update=True,
  5297. layer=0,
  5298. tolerance=None))
  5299. if self.is_legacy is True:
  5300. self.move_tool.sel_shapes.redraw()
  5301. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5302. """
  5303. Will draw a selection shape when dragging mouse on canvas.
  5304. :param old_coords: Old coordinates
  5305. :param coords: New coordinates
  5306. :param kwargs: Keyword arguments
  5307. :return:
  5308. """
  5309. if 'color' in kwargs:
  5310. color = kwargs['color']
  5311. else:
  5312. color = self.defaults['global_sel_line']
  5313. if 'face_color' in kwargs:
  5314. face_color = kwargs['face_color']
  5315. else:
  5316. face_color = self.defaults['global_sel_fill']
  5317. if 'face_alpha' in kwargs:
  5318. face_alpha = kwargs['face_alpha']
  5319. else:
  5320. face_alpha = 0.3
  5321. x0, y0 = old_coords
  5322. x1, y1 = coords
  5323. pt1 = (x0, y0)
  5324. pt2 = (x1, y0)
  5325. pt3 = (x1, y1)
  5326. pt4 = (x0, y1)
  5327. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5328. # color_t = Color(face_color)
  5329. # color_t.alpha = face_alpha
  5330. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5331. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5332. layer=0, tolerance=None)
  5333. if self.is_legacy is True:
  5334. self.move_tool.sel_shapes.redraw()
  5335. def on_file_new_click(self):
  5336. """
  5337. Callback for menu item File -> New.
  5338. Executed on clicking the Menu -> File -> New Project
  5339. :return:
  5340. """
  5341. if self.collection.get_list() and self.should_we_save:
  5342. msgbox = QtWidgets.QMessageBox()
  5343. # msgbox.setText("<B>Save changes ...</B>")
  5344. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5345. "Creating a New project will delete them.\n"
  5346. "Do you want to Save the project?"))
  5347. msgbox.setWindowTitle(_("Save changes"))
  5348. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5349. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5350. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5351. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5352. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5353. msgbox.setDefaultButton(bt_yes)
  5354. msgbox.exec_()
  5355. response = msgbox.clickedButton()
  5356. if response == bt_yes:
  5357. self.on_file_saveprojectas()
  5358. elif response == bt_cancel:
  5359. return
  5360. elif response == bt_no:
  5361. self.on_file_new()
  5362. else:
  5363. self.on_file_new()
  5364. self.inform.emit('[success] %s...' % _("New Project created"))
  5365. def on_file_new(self, cli=None):
  5366. """
  5367. Returns the application to its startup state. This method is thread-safe.
  5368. :param cli: Boolean. If True this method was run from command line
  5369. :return: None
  5370. """
  5371. self.defaults.report_usage("on_file_new")
  5372. # Remove everything from memory
  5373. App.log.debug("on_file_new()")
  5374. # close any editor that might be open
  5375. if self.call_source != 'app':
  5376. self.editor2object(cleanup=True)
  5377. # ## EDITOR section
  5378. self.geo_editor = FlatCAMGeoEditor(self)
  5379. self.exc_editor = FlatCAMExcEditor(self)
  5380. self.grb_editor = FlatCAMGrbEditor(self)
  5381. # Clear pool
  5382. self.clear_pool()
  5383. for obj in self.collection.get_list():
  5384. # delete shapes left drawn from mark shape_collections, if any
  5385. if isinstance(obj, GerberObject):
  5386. try:
  5387. for el in obj.mark_shapes:
  5388. obj.mark_shapes[el].clear(update=True)
  5389. obj.mark_shapes[el].enabled = False
  5390. del el
  5391. except AttributeError:
  5392. pass
  5393. # also delete annotation shapes, if any
  5394. elif isinstance(obj, CNCJobObject):
  5395. try:
  5396. obj.text_col.enabled = False
  5397. del obj.text_col
  5398. obj.annotation.clear(update=True)
  5399. del obj.annotation
  5400. except AttributeError:
  5401. pass
  5402. # delete the exclusion areas
  5403. self.exc_areas.clear_shapes()
  5404. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5405. self.shell.init_tcl()
  5406. # delete any selection shape on canvas
  5407. self.delete_selection_shape()
  5408. # delete all FlatCAM objects
  5409. self.collection.delete_all()
  5410. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5411. self.setup_component_editor()
  5412. # Clear project filename
  5413. self.project_filename = None
  5414. # Load the application defaults
  5415. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5416. # Re-fresh project options
  5417. self.on_options_app2project()
  5418. # Init FlatCAMTools
  5419. self.init_tools()
  5420. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5421. if cli is None:
  5422. # we need to go in reverse because once we remove a tab then the index changes
  5423. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5424. # and so on. Therefore the deletion should be done in reverse
  5425. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5426. for index in range(wdg_count, -1, -1):
  5427. try:
  5428. self.ui.plot_tab_area.closeTab(index)
  5429. except Exception as e:
  5430. log.debug("App.on_file_new() --> %s" % str(e))
  5431. # # And then add again the Plot Area
  5432. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5433. self.ui.plot_tab_area.protectTab(0)
  5434. # take the focus of the Notebook on Project Tab.
  5435. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5436. self.set_ui_title(name=_("New Project - Not saved"))
  5437. def obj_properties(self):
  5438. """
  5439. Will launch the object Properties Tool
  5440. :return:
  5441. """
  5442. self.defaults.report_usage("obj_properties()")
  5443. self.properties_tool.run(toggle=False)
  5444. def on_project_context_save(self):
  5445. """
  5446. Wrapper, will save the object function of it's type
  5447. :return:
  5448. """
  5449. obj = self.collection.get_active()
  5450. if type(obj) == GeometryObject:
  5451. self.on_file_exportdxf()
  5452. elif type(obj) == ExcellonObject:
  5453. self.on_file_saveexcellon()
  5454. elif type(obj) == CNCJobObject:
  5455. obj.on_exportgcode_button_click()
  5456. elif type(obj) == GerberObject:
  5457. self.on_file_savegerber()
  5458. elif type(obj) == ScriptObject:
  5459. self.on_file_savescript()
  5460. elif type(obj) == DocumentObject:
  5461. self.on_file_savedocument()
  5462. def obj_move(self):
  5463. """
  5464. Callback for the Move menu entry in various Context Menu's.
  5465. :return:
  5466. """
  5467. self.defaults.report_usage("obj_move()")
  5468. self.move_tool.run(toggle=False)
  5469. def on_fileopengerber(self, signal, name=None):
  5470. """
  5471. File menu callback for opening a Gerber.
  5472. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5473. :param name:
  5474. :return: None
  5475. """
  5476. self.defaults.report_usage("on_fileopengerber")
  5477. App.log.debug("on_fileopengerber()")
  5478. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5479. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5480. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5481. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5482. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5483. "*.mil);;" \
  5484. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5485. "Allegro Files (*.art);;" \
  5486. "Mentor Files (*.pho *.gdo);;" \
  5487. "All Files (*.*)"
  5488. if name is None:
  5489. try:
  5490. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5491. directory=self.get_last_folder(),
  5492. filter=_filter_,
  5493. initialFilter=self.last_op_gerber_filter)
  5494. except TypeError:
  5495. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5496. filenames = [str(filename) for filename in filenames]
  5497. self.last_op_gerber_filter = _f
  5498. else:
  5499. filenames = [name]
  5500. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5501. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5502. _("Opening Gerber file.")),
  5503. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5504. color=QtGui.QColor("gray"))
  5505. if len(filenames) == 0:
  5506. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5507. else:
  5508. for filename in filenames:
  5509. if filename != '':
  5510. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5511. def on_fileopenexcellon(self, signal, name=None):
  5512. """
  5513. File menu callback for opening an Excellon file.
  5514. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5515. :param name:
  5516. :return: None
  5517. """
  5518. self.defaults.report_usage("on_fileopenexcellon")
  5519. App.log.debug("on_fileopenexcellon()")
  5520. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5521. "All Files (*.*)"
  5522. if name is None:
  5523. try:
  5524. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5525. directory=self.get_last_folder(),
  5526. filter=_filter_,
  5527. initialFilter=self.last_op_excellon_filter)
  5528. except TypeError:
  5529. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5530. filenames = [str(filename) for filename in filenames]
  5531. self.last_op_excellon_filter = _f
  5532. else:
  5533. filenames = [str(name)]
  5534. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5535. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5536. _("Opening Excellon file.")),
  5537. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5538. color=QtGui.QColor("gray"))
  5539. if len(filenames) == 0:
  5540. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5541. else:
  5542. for filename in filenames:
  5543. if filename != '':
  5544. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5545. def on_fileopengcode(self, signal, name=None):
  5546. """
  5547. File menu call back for opening gcode.
  5548. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5549. :param name:
  5550. :return:
  5551. """
  5552. self.defaults.report_usage("on_fileopengcode")
  5553. App.log.debug("on_fileopengcode()")
  5554. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5555. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5556. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5557. "All Files (*.*)"
  5558. if name is None:
  5559. try:
  5560. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5561. directory=self.get_last_folder(),
  5562. filter=_filter_,
  5563. initialFilter=self.last_op_gcode_filter)
  5564. except TypeError:
  5565. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5566. filenames = [str(filename) for filename in filenames]
  5567. self.last_op_gcode_filter = _f
  5568. else:
  5569. filenames = [name]
  5570. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5571. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5572. _("Opening G-Code file.")),
  5573. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5574. color=QtGui.QColor("gray"))
  5575. if len(filenames) == 0:
  5576. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5577. else:
  5578. for filename in filenames:
  5579. if filename != '':
  5580. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5581. def on_file_openproject(self, signal):
  5582. """
  5583. File menu callback for opening a project.
  5584. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5585. :return: None
  5586. """
  5587. self.defaults.report_usage("on_file_openproject")
  5588. App.log.debug("on_file_openproject()")
  5589. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5590. try:
  5591. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5592. directory=self.get_last_folder(), filter=_filter_)
  5593. except TypeError:
  5594. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5595. # The Qt methods above will return a QString which can cause problems later.
  5596. # So far json.dump() will fail to serialize it.
  5597. # TODO: Improve the serialization methods and remove this fix.
  5598. filename = str(filename)
  5599. if filename == "":
  5600. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5601. else:
  5602. # self.worker_task.emit({'fcn': self.open_project,
  5603. # 'params': [filename]})
  5604. # The above was failing because open_project() is not
  5605. # thread safe. The new_project()
  5606. self.open_project(filename)
  5607. def on_fileopenhpgl2(self, signal, name=None):
  5608. """
  5609. File menu callback for opening a HPGL2.
  5610. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5611. :param name:
  5612. :return: None
  5613. """
  5614. self.defaults.report_usage("on_fileopenhpgl2")
  5615. App.log.debug("on_fileopenhpgl2()")
  5616. _filter_ = "HPGL2 Files (*.plt);;" \
  5617. "All Files (*.*)"
  5618. if name is None:
  5619. try:
  5620. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5621. directory=self.get_last_folder(),
  5622. filter=_filter_)
  5623. except TypeError:
  5624. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5625. filenames = [str(filename) for filename in filenames]
  5626. else:
  5627. filenames = [name]
  5628. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5629. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5630. _("Opening HPGL2 file.")),
  5631. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5632. color=QtGui.QColor("gray"))
  5633. if len(filenames) == 0:
  5634. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5635. else:
  5636. for filename in filenames:
  5637. if filename != '':
  5638. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5639. def on_file_openconfig(self, signal):
  5640. """
  5641. File menu callback for opening a config file.
  5642. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5643. :return: None
  5644. """
  5645. self.defaults.report_usage("on_file_openconfig")
  5646. App.log.debug("on_file_openconfig()")
  5647. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5648. try:
  5649. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5650. directory=self.data_path, filter=_filter_)
  5651. except TypeError:
  5652. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5653. filter=_filter_)
  5654. if filename == "":
  5655. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5656. else:
  5657. self.open_config_file(filename)
  5658. def on_file_exportsvg(self):
  5659. """
  5660. Callback for menu item File->Export SVG.
  5661. :return: None
  5662. """
  5663. self.defaults.report_usage("on_file_exportsvg")
  5664. App.log.debug("on_file_exportsvg()")
  5665. obj = self.collection.get_active()
  5666. if obj is None:
  5667. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5668. msg = _("Please Select a Geometry object to export")
  5669. msgbox = QtWidgets.QMessageBox()
  5670. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5671. msgbox.setInformativeText(msg)
  5672. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5673. msgbox.setDefaultButton(bt_ok)
  5674. msgbox.exec_()
  5675. return
  5676. # Check for more compatible types and add as required
  5677. if (not isinstance(obj, GeometryObject)
  5678. and not isinstance(obj, GerberObject)
  5679. and not isinstance(obj, CNCJobObject)
  5680. and not isinstance(obj, ExcellonObject)):
  5681. msg = '[ERROR_NOTCL] %s' % \
  5682. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5683. msgbox = QtWidgets.QMessageBox()
  5684. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5685. msgbox.setInformativeText(msg)
  5686. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5687. msgbox.setDefaultButton(bt_ok)
  5688. msgbox.exec_()
  5689. return
  5690. name = obj.options["name"]
  5691. _filter = "SVG File (*.svg);;All Files (*.*)"
  5692. try:
  5693. filename, _f = FCFileSaveDialog.get_saved_filename(
  5694. caption=_("Export SVG"),
  5695. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5696. ext_filter=_filter)
  5697. except TypeError:
  5698. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5699. filename = str(filename)
  5700. if filename == "":
  5701. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5702. return
  5703. else:
  5704. self.export_svg(name, filename)
  5705. if self.defaults["global_open_style"] is False:
  5706. self.file_opened.emit("SVG", filename)
  5707. self.file_saved.emit("SVG", filename)
  5708. def on_file_exportpng(self):
  5709. self.defaults.report_usage("on_file_exportpng")
  5710. App.log.debug("on_file_exportpng()")
  5711. self.date = str(datetime.today()).rpartition('.')[0]
  5712. self.date = ''.join(c for c in self.date if c not in ':-')
  5713. self.date = self.date.replace(' ', '_')
  5714. data = None
  5715. if self.is_legacy is False:
  5716. image = _screenshot(alpha=False)
  5717. data = np.asarray(image)
  5718. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5719. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5720. return
  5721. filter_ = "PNG File (*.png);;All Files (*.*)"
  5722. try:
  5723. filename, _f = FCFileSaveDialog.get_saved_filename(
  5724. caption=_("Export PNG Image"),
  5725. directory=self.get_last_save_folder() + '/png_' + self.date,
  5726. ext_filter=filter_)
  5727. except TypeError:
  5728. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5729. filename = str(filename)
  5730. if filename == "":
  5731. self.inform.emit(_("Cancelled."))
  5732. return
  5733. else:
  5734. if self.is_legacy is False:
  5735. write_png(filename, data)
  5736. else:
  5737. self.plotcanvas.figure.savefig(filename)
  5738. if self.defaults["global_open_style"] is False:
  5739. self.file_opened.emit("png", filename)
  5740. self.file_saved.emit("png", filename)
  5741. def on_file_savegerber(self):
  5742. """
  5743. Callback for menu item in Project context menu.
  5744. :return: None
  5745. """
  5746. self.defaults.report_usage("on_file_savegerber")
  5747. App.log.debug("on_file_savegerber()")
  5748. obj = self.collection.get_active()
  5749. if obj is None:
  5750. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5751. return
  5752. # Check for more compatible types and add as required
  5753. if not isinstance(obj, GerberObject):
  5754. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5755. return
  5756. name = self.collection.get_active().options["name"]
  5757. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5758. try:
  5759. filename, _f = FCFileSaveDialog.get_saved_filename(
  5760. caption="Save Gerber source file",
  5761. directory=self.get_last_save_folder() + '/' + name,
  5762. ext_filter=_filter)
  5763. except TypeError:
  5764. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5765. filename = str(filename)
  5766. if filename == "":
  5767. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5768. return
  5769. else:
  5770. self.save_source_file(name, filename)
  5771. if self.defaults["global_open_style"] is False:
  5772. self.file_opened.emit("Gerber", filename)
  5773. self.file_saved.emit("Gerber", filename)
  5774. def on_file_savescript(self):
  5775. """
  5776. Callback for menu item in Project context menu.
  5777. :return: None
  5778. """
  5779. self.defaults.report_usage("on_file_savescript")
  5780. App.log.debug("on_file_savescript()")
  5781. obj = self.collection.get_active()
  5782. if obj is None:
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5784. return
  5785. # Check for more compatible types and add as required
  5786. if not isinstance(obj, ScriptObject):
  5787. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5788. return
  5789. name = self.collection.get_active().options["name"]
  5790. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5791. try:
  5792. filename, _f = FCFileSaveDialog.get_saved_filename(
  5793. caption="Save Script source file",
  5794. directory=self.get_last_save_folder() + '/' + name,
  5795. ext_filter=_filter)
  5796. except TypeError:
  5797. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5798. filename = str(filename)
  5799. if filename == "":
  5800. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5801. return
  5802. else:
  5803. self.save_source_file(name, filename)
  5804. if self.defaults["global_open_style"] is False:
  5805. self.file_opened.emit("Script", filename)
  5806. self.file_saved.emit("Script", filename)
  5807. def on_file_savedocument(self):
  5808. """
  5809. Callback for menu item in Project context menu.
  5810. :return: None
  5811. """
  5812. self.defaults.report_usage("on_file_savedocument")
  5813. App.log.debug("on_file_savedocument()")
  5814. obj = self.collection.get_active()
  5815. if obj is None:
  5816. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5817. return
  5818. # Check for more compatible types and add as required
  5819. if not isinstance(obj, ScriptObject):
  5820. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5821. return
  5822. name = self.collection.get_active().options["name"]
  5823. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5824. try:
  5825. filename, _f = FCFileSaveDialog.get_saved_filename(
  5826. caption="Save Document source file",
  5827. directory=self.get_last_save_folder() + '/' + name,
  5828. ext_filter=_filter)
  5829. except TypeError:
  5830. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5831. ext_filter=_filter)
  5832. filename = str(filename)
  5833. if filename == "":
  5834. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5835. return
  5836. else:
  5837. self.save_source_file(name, filename)
  5838. if self.defaults["global_open_style"] is False:
  5839. self.file_opened.emit("Document", filename)
  5840. self.file_saved.emit("Document", filename)
  5841. def on_file_saveexcellon(self):
  5842. """
  5843. Callback for menu item in project context menu.
  5844. :return: None
  5845. """
  5846. self.defaults.report_usage("on_file_saveexcellon")
  5847. App.log.debug("on_file_saveexcellon()")
  5848. obj = self.collection.get_active()
  5849. if obj is None:
  5850. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5851. return
  5852. # Check for more compatible types and add as required
  5853. if not isinstance(obj, ExcellonObject):
  5854. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5855. return
  5856. name = self.collection.get_active().options["name"]
  5857. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5858. try:
  5859. filename, _f = FCFileSaveDialog.get_saved_filename(
  5860. caption=_("Save Excellon source file"),
  5861. directory=self.get_last_save_folder() + '/' + name,
  5862. ext_filter=_filter)
  5863. except TypeError:
  5864. filename, _f = FCFileSaveDialog.get_saved_filename(
  5865. caption=_("Save Excellon source file"), ext_filter=_filter)
  5866. filename = str(filename)
  5867. if filename == "":
  5868. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5869. return
  5870. else:
  5871. self.save_source_file(name, filename)
  5872. if self.defaults["global_open_style"] is False:
  5873. self.file_opened.emit("Excellon", filename)
  5874. self.file_saved.emit("Excellon", filename)
  5875. def on_file_exportexcellon(self):
  5876. """
  5877. Callback for menu item File->Export->Excellon.
  5878. :return: None
  5879. """
  5880. self.defaults.report_usage("on_file_exportexcellon")
  5881. App.log.debug("on_file_exportexcellon()")
  5882. obj = self.collection.get_active()
  5883. if obj is None:
  5884. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5885. return
  5886. # Check for more compatible types and add as required
  5887. if not isinstance(obj, ExcellonObject):
  5888. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5889. return
  5890. name = self.collection.get_active().options["name"]
  5891. _filter = self.defaults["excellon_save_filters"]
  5892. try:
  5893. filename, _f = FCFileSaveDialog.get_saved_filename(
  5894. caption=_("Export Excellon"),
  5895. directory=self.get_last_save_folder() + '/' + name,
  5896. ext_filter=_filter)
  5897. except TypeError:
  5898. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5899. filename = str(filename)
  5900. if filename == "":
  5901. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5902. return
  5903. else:
  5904. used_extension = filename.rpartition('.')[2]
  5905. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5906. self.export_excellon(name, filename)
  5907. if self.defaults["global_open_style"] is False:
  5908. self.file_opened.emit("Excellon", filename)
  5909. self.file_saved.emit("Excellon", filename)
  5910. def on_file_exportgerber(self):
  5911. """
  5912. Callback for menu item File->Export->Gerber.
  5913. :return: None
  5914. """
  5915. self.defaults.report_usage("on_file_exportgerber")
  5916. App.log.debug("on_file_exportgerber()")
  5917. obj = self.collection.get_active()
  5918. if obj is None:
  5919. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5920. return
  5921. # Check for more compatible types and add as required
  5922. if not isinstance(obj, GerberObject):
  5923. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5924. return
  5925. name = self.collection.get_active().options["name"]
  5926. _filter_ = self.defaults['gerber_save_filters']
  5927. try:
  5928. filename, _f = FCFileSaveDialog.get_saved_filename(
  5929. caption=_("Export Gerber"),
  5930. directory=self.get_last_save_folder() + '/' + name,
  5931. ext_filter=_filter_)
  5932. except TypeError:
  5933. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5934. filename = str(filename)
  5935. if filename == "":
  5936. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5937. return
  5938. else:
  5939. used_extension = filename.rpartition('.')[2]
  5940. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5941. self.export_gerber(name, filename)
  5942. if self.defaults["global_open_style"] is False:
  5943. self.file_opened.emit("Gerber", filename)
  5944. self.file_saved.emit("Gerber", filename)
  5945. def on_file_exportdxf(self):
  5946. """
  5947. Callback for menu item File->Export DXF.
  5948. :return: None
  5949. """
  5950. self.defaults.report_usage("on_file_exportdxf")
  5951. App.log.debug("on_file_exportdxf()")
  5952. obj = self.collection.get_active()
  5953. if obj is None:
  5954. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5955. msg = _("Please Select a Geometry object to export")
  5956. msgbox = QtWidgets.QMessageBox()
  5957. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5958. msgbox.setInformativeText(msg)
  5959. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5960. msgbox.setDefaultButton(bt_ok)
  5961. msgbox.exec_()
  5962. return
  5963. # Check for more compatible types and add as required
  5964. if not isinstance(obj, GeometryObject):
  5965. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5966. msgbox = QtWidgets.QMessageBox()
  5967. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5968. msgbox.setInformativeText(msg)
  5969. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5970. msgbox.setDefaultButton(bt_ok)
  5971. msgbox.exec_()
  5972. return
  5973. name = self.collection.get_active().options["name"]
  5974. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5975. try:
  5976. filename, _f = FCFileSaveDialog.get_saved_filename(
  5977. caption=_("Export DXF"),
  5978. directory=self.get_last_save_folder() + '/' + name,
  5979. ext_filter=_filter_)
  5980. except TypeError:
  5981. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  5982. filename = str(filename)
  5983. if filename == "":
  5984. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5985. return
  5986. else:
  5987. self.export_dxf(name, filename)
  5988. if self.defaults["global_open_style"] is False:
  5989. self.file_opened.emit("DXF", filename)
  5990. self.file_saved.emit("DXF", filename)
  5991. def on_file_importsvg(self, type_of_obj):
  5992. """
  5993. Callback for menu item File->Import SVG.
  5994. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5995. :type type_of_obj: str
  5996. :return: None
  5997. """
  5998. self.defaults.report_usage("on_file_importsvg")
  5999. App.log.debug("on_file_importsvg()")
  6000. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6001. try:
  6002. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6003. directory=self.get_last_folder(), filter=_filter_)
  6004. except TypeError:
  6005. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6006. filter=_filter_)
  6007. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6008. type_of_obj = "geometry"
  6009. filenames = [str(filename) for filename in filenames]
  6010. if len(filenames) == 0:
  6011. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6012. else:
  6013. for filename in filenames:
  6014. if filename != '':
  6015. self.worker_task.emit({'fcn': self.import_svg,
  6016. 'params': [filename, type_of_obj]})
  6017. def on_file_importdxf(self, type_of_obj):
  6018. """
  6019. Callback for menu item File->Import DXF.
  6020. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6021. :type type_of_obj: str
  6022. :return: None
  6023. """
  6024. self.defaults.report_usage("on_file_importdxf")
  6025. App.log.debug("on_file_importdxf()")
  6026. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6027. try:
  6028. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6029. directory=self.get_last_folder(),
  6030. filter=_filter_)
  6031. except TypeError:
  6032. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6033. filter=_filter_)
  6034. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6035. type_of_obj = "geometry"
  6036. filenames = [str(filename) for filename in filenames]
  6037. if len(filenames) == 0:
  6038. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6039. else:
  6040. for filename in filenames:
  6041. if filename != '':
  6042. self.worker_task.emit({'fcn': self.import_dxf,
  6043. 'params': [filename, type_of_obj]})
  6044. # ###############################################################################################################
  6045. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6046. # ###############################################################################################################
  6047. def init_code_editor(self, name):
  6048. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6049. # add the tab if it was closed
  6050. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6051. self.text_editor_tab.setObjectName('text_editor_tab')
  6052. # delete the absolute and relative position and messages in the infobar
  6053. self.ui.position_label.setText("")
  6054. # self.ui.rel_position_label.setText("")
  6055. # first clear previous text in text editor (if any)
  6056. self.text_editor_tab.code_editor.clear()
  6057. self.text_editor_tab.code_editor.setReadOnly(False)
  6058. self.toggle_codeeditor = True
  6059. self.text_editor_tab.code_editor.completer_enable = False
  6060. self.text_editor_tab.buttonRun.hide()
  6061. # make sure to keep a reference to the code editor
  6062. self.reference_code_editor = self.text_editor_tab.code_editor
  6063. # Switch plot_area to CNCJob tab
  6064. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6065. def on_view_source(self):
  6066. """
  6067. Called when the user wants to see the source file of the selected object
  6068. :return:
  6069. """
  6070. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6071. self.proc_container.view.set_busy(_("Loading..."))
  6072. try:
  6073. obj = self.collection.get_active()
  6074. except Exception as e:
  6075. log.debug("App.on_view_source() --> %s" % str(e))
  6076. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6077. return 'fail'
  6078. if obj is None:
  6079. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6080. return 'fail'
  6081. flt = "All Files (*.*)"
  6082. if obj.kind == 'gerber':
  6083. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6084. elif obj.kind == 'excellon':
  6085. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6086. elif obj.kind == 'cncjob':
  6087. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6088. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6089. # add the tab if it was closed
  6090. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6091. self.source_editor_tab.setObjectName('source_editor_tab')
  6092. # delete the absolute and relative position and messages in the infobar
  6093. self.ui.position_label.setText("")
  6094. # self.ui.rel_position_label.setText("")
  6095. # first clear previous text in text editor (if any)
  6096. self.source_editor_tab.code_editor.clear()
  6097. self.source_editor_tab.code_editor.setReadOnly(False)
  6098. self.source_editor_tab.code_editor.completer_enable = False
  6099. self.source_editor_tab.buttonRun.hide()
  6100. # Switch plot_area to CNCJob tab
  6101. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6102. try:
  6103. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6104. except TypeError:
  6105. pass
  6106. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6107. try:
  6108. self.source_editor_tab.buttonSave.clicked.disconnect()
  6109. except TypeError:
  6110. pass
  6111. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6112. # then append the text from GCode to the text editor
  6113. if obj.kind == 'cncjob':
  6114. try:
  6115. file = obj.export_gcode(
  6116. preamble=self.defaults["cncjob_prepend"],
  6117. postamble=self.defaults["cncjob_append"],
  6118. to_file=True)
  6119. if file == 'fail':
  6120. return 'fail'
  6121. except AttributeError:
  6122. self.inform.emit('[WARNING_NOTCL] %s' %
  6123. _("There is no selected object for which to see it's source file code."))
  6124. return 'fail'
  6125. else:
  6126. try:
  6127. file = StringIO(obj.source_file)
  6128. except (AttributeError, TypeError):
  6129. self.inform.emit('[WARNING_NOTCL] %s' %
  6130. _("There is no selected object for which to see it's source file code."))
  6131. return 'fail'
  6132. self.source_editor_tab.t_frame.hide()
  6133. try:
  6134. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6135. # for line in file:
  6136. # QtWidgets.QApplication.processEvents()
  6137. # proc_line = str(line).strip('\n')
  6138. # self.source_editor_tab.code_editor.append(proc_line)
  6139. except Exception as e:
  6140. log.debug('App.on_view_source() -->%s' % str(e))
  6141. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6142. return
  6143. self.source_editor_tab.handleTextChanged()
  6144. self.source_editor_tab.t_frame.show()
  6145. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6146. self.proc_container.view.set_idle()
  6147. # self.ui.show()
  6148. def on_toggle_code_editor(self):
  6149. self.defaults.report_usage("on_toggle_code_editor()")
  6150. if self.toggle_codeeditor is False:
  6151. self.init_code_editor(name=_("Code Editor"))
  6152. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6153. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6154. self.text_editor_tab.buttonSave.clicked.disconnect()
  6155. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6156. else:
  6157. for idx in range(self.ui.plot_tab_area.count()):
  6158. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6159. self.ui.plot_tab_area.closeTab(idx)
  6160. break
  6161. self.toggle_codeeditor = False
  6162. def on_code_editor_close(self):
  6163. self.toggle_codeeditor = False
  6164. def goto_text_line(self):
  6165. """
  6166. Will scroll a text to the specified text line.
  6167. :return: None
  6168. """
  6169. dia_box = Dialog_box(title=_("Go to Line ..."),
  6170. label=_("Line:"),
  6171. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6172. initial_text='')
  6173. try:
  6174. line = int(dia_box.location) - 1
  6175. except (ValueError, TypeError):
  6176. line = 0
  6177. if dia_box.ok:
  6178. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6179. # at the top of the window
  6180. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6181. # get the document() of the TextEditor
  6182. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6183. # create a Text Cursor based on the searched line
  6184. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6185. # set cursor of the code editor with the cursor at the searcehd line
  6186. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6187. def on_filenewscript(self, silent=False):
  6188. """
  6189. Will create a new script file and open it in the Code Editor
  6190. :param silent: if True will not display status messages
  6191. :return: None
  6192. """
  6193. if silent is False:
  6194. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6195. # delete the absolute and relative position and messages in the infobar
  6196. self.ui.position_label.setText("")
  6197. # self.ui.rel_position_label.setText("")
  6198. self.app_obj.new_script_object()
  6199. # script_text = script_obj.source_file
  6200. #
  6201. # self.proc_container.view.set_busy(_("Loading..."))
  6202. # script_obj.script_editor_tab.t_frame.hide()
  6203. #
  6204. # script_obj.script_editor_tab.t_frame.show()
  6205. # self.proc_container.view.set_idle()
  6206. def on_fileopenscript(self, name=None, silent=False):
  6207. """
  6208. Will open a Tcl script file into the Code Editor
  6209. :param silent: if True will not display status messages
  6210. :param name: name of a Tcl script file to open
  6211. :return: None
  6212. """
  6213. self.defaults.report_usage("on_fileopenscript")
  6214. App.log.debug("on_fileopenscript()")
  6215. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6216. "All Files (*.*)"
  6217. if name:
  6218. filenames = [name]
  6219. else:
  6220. try:
  6221. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6222. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6223. except TypeError:
  6224. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6225. if len(filenames) == 0:
  6226. if silent is False:
  6227. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6228. else:
  6229. for filename in filenames:
  6230. if filename != '':
  6231. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6232. def on_fileopenscript_example(self, name=None, silent=False):
  6233. """
  6234. Will open a Tcl script file into the Code Editor
  6235. :param silent: if True will not display status messages
  6236. :param name: name of a Tcl script file to open
  6237. :return:
  6238. """
  6239. self.defaults.report_usage("on_fileopenscript_example")
  6240. log.debug("on_fileopenscript_example()")
  6241. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6242. "All Files (*.*)"
  6243. # test if the app was frozen and choose the path for the configuration file
  6244. if getattr(sys, "frozen", False) is True:
  6245. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6246. else:
  6247. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6248. if name:
  6249. filenames = [name]
  6250. else:
  6251. try:
  6252. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6253. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6254. except TypeError:
  6255. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6256. if len(filenames) == 0:
  6257. if silent is False:
  6258. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6259. else:
  6260. for filename in filenames:
  6261. if filename != '':
  6262. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6263. def on_filerunscript(self, name=None, silent=False):
  6264. """
  6265. File menu callback for loading and running a TCL script.
  6266. :param silent: if True will not display status messages
  6267. :param name: name of a Tcl script file to be run by FlatCAM
  6268. :return: None
  6269. """
  6270. self.defaults.report_usage("on_filerunscript")
  6271. App.log.debug("on_file_runscript()")
  6272. if name:
  6273. filename = name
  6274. if self.cmd_line_headless != 1:
  6275. self.splash.showMessage('%s: %ssec\n%s' %
  6276. (_("Canvas initialization started.\n"
  6277. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6278. _("Executing ScriptObject file.")
  6279. ),
  6280. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6281. color=QtGui.QColor("gray"))
  6282. else:
  6283. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6284. "All Files (*.*)"
  6285. try:
  6286. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6287. directory=self.get_last_folder(), filter=_filter_)
  6288. except TypeError:
  6289. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6290. # The Qt methods above will return a QString which can cause problems later.
  6291. # So far json.dump() will fail to serialize it.
  6292. filename = str(filename)
  6293. if filename == "":
  6294. if silent is False:
  6295. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6296. else:
  6297. if self.cmd_line_headless != 1:
  6298. if self.ui.shell_dock.isHidden():
  6299. self.ui.shell_dock.show()
  6300. try:
  6301. with open(filename, "r") as tcl_script:
  6302. cmd_line_shellfile_content = tcl_script.read()
  6303. if self.cmd_line_headless != 1:
  6304. self.shell.exec_command(cmd_line_shellfile_content)
  6305. else:
  6306. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6307. if silent is False:
  6308. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6309. except Exception as e:
  6310. log.debug("App.on_filerunscript() -> %s" % str(e))
  6311. sys.exit(2)
  6312. def on_file_saveproject(self, silent=False):
  6313. """
  6314. Callback for menu item File->Save Project. Saves the project to
  6315. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6316. if set to None. The project is saved by calling ``self.save_project()``.
  6317. :param silent: if True will not display status messages
  6318. :return: None
  6319. """
  6320. self.defaults.report_usage("on_file_saveproject")
  6321. if self.project_filename is None:
  6322. self.on_file_saveprojectas()
  6323. else:
  6324. self.worker_task.emit({'fcn': self.save_project,
  6325. 'params': [self.project_filename, silent]})
  6326. if self.defaults["global_open_style"] is False:
  6327. self.file_opened.emit("project", self.project_filename)
  6328. self.file_saved.emit("project", self.project_filename)
  6329. self.set_ui_title(name=self.project_filename)
  6330. self.should_we_save = False
  6331. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6332. """
  6333. Callback for menu item File->Save Project As... Opens a file
  6334. chooser and saves the project to the given file via
  6335. ``self.save_project()``.
  6336. :param make_copy if to be create a copy of the project; boolean
  6337. :param use_thread: if to be run in a separate thread; boolean
  6338. :param quit_action: if to be followed by quiting the application; boolean
  6339. :return: None
  6340. """
  6341. self.defaults.report_usage("on_file_saveprojectas")
  6342. self.date = str(datetime.today()).rpartition('.')[0]
  6343. self.date = ''.join(c for c in self.date if c not in ':-')
  6344. self.date = self.date.replace(' ', '_')
  6345. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6346. try:
  6347. filename, _f = FCFileSaveDialog.get_saved_filename(
  6348. caption=_("Save Project As ..."),
  6349. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6350. proj=_("Project")),
  6351. ext_filter=filter_
  6352. )
  6353. except TypeError:
  6354. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6355. filename = str(filename)
  6356. if filename == '':
  6357. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6358. return
  6359. if use_thread is True:
  6360. self.worker_task.emit({'fcn': self.save_project,
  6361. 'params': [filename, quit_action]})
  6362. else:
  6363. self.save_project(filename, quit_action)
  6364. # self.save_project(filename)
  6365. if self.defaults["global_open_style"] is False:
  6366. self.file_opened.emit("project", filename)
  6367. self.file_saved.emit("project", filename)
  6368. if not make_copy:
  6369. self.project_filename = filename
  6370. self.set_ui_title(name=self.project_filename)
  6371. self.should_we_save = False
  6372. def on_file_save_objects_pdf(self, use_thread=True):
  6373. self.date = str(datetime.today()).rpartition('.')[0]
  6374. self.date = ''.join(c for c in self.date if c not in ':-')
  6375. self.date = self.date.replace(' ', '_')
  6376. try:
  6377. obj_selection = self.collection.get_selected()
  6378. if len(obj_selection) == 1:
  6379. obj_name = str(obj_selection[0].options['name'])
  6380. else:
  6381. obj_name = _("FlatCAM objects print")
  6382. except AttributeError as err:
  6383. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6384. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6385. return
  6386. if not obj_selection:
  6387. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6388. return
  6389. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6390. try:
  6391. filename, _f = FCFileSaveDialog.get_saved_filename(
  6392. caption=_("Save Object as PDF ..."),
  6393. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6394. obj_name=obj_name,
  6395. date=self.date),
  6396. ext_filter=filter_
  6397. )
  6398. except TypeError:
  6399. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6400. filename = str(filename)
  6401. if filename == '':
  6402. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6403. return
  6404. if use_thread is True:
  6405. self.proc_container.new(_("Printing PDF ... Please wait."))
  6406. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6407. else:
  6408. self.save_pdf(filename, obj_selection)
  6409. # self.save_project(filename)
  6410. if self.defaults["global_open_style"] is False:
  6411. self.file_opened.emit("pdf", filename)
  6412. self.file_saved.emit("pdf", filename)
  6413. def save_pdf(self, file_name, obj_selection):
  6414. p_size = self.defaults['global_workspaceT']
  6415. orientation = self.defaults['global_workspace_orientation']
  6416. color = 'black'
  6417. transparency_level = 1.0
  6418. self.pagesize = {}
  6419. self.pagesize.update(
  6420. {
  6421. 'Bounds': None,
  6422. 'A0': (841 * mm, 1189 * mm),
  6423. 'A1': (594 * mm, 841 * mm),
  6424. 'A2': (420 * mm, 594 * mm),
  6425. 'A3': (297 * mm, 420 * mm),
  6426. 'A4': (210 * mm, 297 * mm),
  6427. 'A5': (148 * mm, 210 * mm),
  6428. 'A6': (105 * mm, 148 * mm),
  6429. 'A7': (74 * mm, 105 * mm),
  6430. 'A8': (52 * mm, 74 * mm),
  6431. 'A9': (37 * mm, 52 * mm),
  6432. 'A10': (26 * mm, 37 * mm),
  6433. 'B0': (1000 * mm, 1414 * mm),
  6434. 'B1': (707 * mm, 1000 * mm),
  6435. 'B2': (500 * mm, 707 * mm),
  6436. 'B3': (353 * mm, 500 * mm),
  6437. 'B4': (250 * mm, 353 * mm),
  6438. 'B5': (176 * mm, 250 * mm),
  6439. 'B6': (125 * mm, 176 * mm),
  6440. 'B7': (88 * mm, 125 * mm),
  6441. 'B8': (62 * mm, 88 * mm),
  6442. 'B9': (44 * mm, 62 * mm),
  6443. 'B10': (31 * mm, 44 * mm),
  6444. 'C0': (917 * mm, 1297 * mm),
  6445. 'C1': (648 * mm, 917 * mm),
  6446. 'C2': (458 * mm, 648 * mm),
  6447. 'C3': (324 * mm, 458 * mm),
  6448. 'C4': (229 * mm, 324 * mm),
  6449. 'C5': (162 * mm, 229 * mm),
  6450. 'C6': (114 * mm, 162 * mm),
  6451. 'C7': (81 * mm, 114 * mm),
  6452. 'C8': (57 * mm, 81 * mm),
  6453. 'C9': (40 * mm, 57 * mm),
  6454. 'C10': (28 * mm, 40 * mm),
  6455. # American paper sizes
  6456. 'LETTER': (8.5 * inch, 11 * inch),
  6457. 'LEGAL': (8.5 * inch, 14 * inch),
  6458. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6459. # From https://en.wikipedia.org/wiki/Paper_size
  6460. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6461. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6462. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6463. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6464. 'LEDGER': (17 * inch, 11 * inch),
  6465. }
  6466. )
  6467. exported_svg = []
  6468. for obj in obj_selection:
  6469. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6470. scale_factor_x=None, scale_factor_y=None,
  6471. skew_factor_x=None, skew_factor_y=None,
  6472. mirror=None)
  6473. if obj.kind.lower() == 'gerber':
  6474. # color = self.defaults["gerber_plot_fill"][:-2]
  6475. color = obj.fill_color[:-2]
  6476. elif obj.kind.lower() == 'excellon':
  6477. color = '#C40000'
  6478. elif obj.kind.lower() == 'geometry':
  6479. color = self.defaults["global_draw_color"]
  6480. # Change the attributes of the exported SVG
  6481. # We don't need stroke-width
  6482. # We set opacity to maximum
  6483. # We set the colour to WHITE
  6484. root = ET.fromstring(svg_obj)
  6485. for child in root:
  6486. child.set('fill', str(color))
  6487. child.set('opacity', str(transparency_level))
  6488. child.set('stroke', str(color))
  6489. exported_svg.append(ET.tostring(root))
  6490. xmin = Inf
  6491. ymin = Inf
  6492. xmax = -Inf
  6493. ymax = -Inf
  6494. for obj in obj_selection:
  6495. try:
  6496. gxmin, gymin, gxmax, gymax = obj.bounds()
  6497. xmin = min([xmin, gxmin])
  6498. ymin = min([ymin, gymin])
  6499. xmax = max([xmax, gxmax])
  6500. ymax = max([ymax, gymax])
  6501. except Exception as e:
  6502. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6503. # Determine bounding area for svg export
  6504. bounds = [xmin, ymin, xmax, ymax]
  6505. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6506. # This contain the measure units
  6507. uom = obj_selection[0].units.lower()
  6508. # Define a boundary around SVG of about 1.0mm (~39mils)
  6509. if uom in "mm":
  6510. boundary = 1.0
  6511. else:
  6512. boundary = 0.0393701
  6513. # Convert everything to strings for use in the xml doc
  6514. svgwidth = str(size[0] + (2 * boundary))
  6515. svgheight = str(size[1] + (2 * boundary))
  6516. minx = str(bounds[0] - boundary)
  6517. miny = str(bounds[1] + boundary + size[1])
  6518. # Add a SVG Header and footer to the svg output from shapely
  6519. # The transform flips the Y Axis so that everything renders
  6520. # properly within svg apps such as inkscape
  6521. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6522. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6523. svg_header += 'width="' + svgwidth + uom + '" '
  6524. svg_header += 'height="' + svgheight + uom + '" '
  6525. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6526. svg_header += '>'
  6527. svg_header += '<g transform="scale(1,-1)">'
  6528. svg_footer = '</g> </svg>'
  6529. svg_elem = str(svg_header)
  6530. for svg_item in exported_svg:
  6531. svg_elem += str(svg_item)
  6532. svg_elem += str(svg_footer)
  6533. # Parse the xml through a xml parser just to add line feeds
  6534. # and to make it look more pretty for the output
  6535. doc = parse_xml_string(svg_elem)
  6536. doc_final = doc.toprettyxml()
  6537. try:
  6538. if self.defaults['units'].upper() == 'IN':
  6539. unit = inch
  6540. else:
  6541. unit = mm
  6542. doc_final = StringIO(doc_final)
  6543. drawing = svg2rlg(doc_final)
  6544. if p_size == 'Bounds':
  6545. renderPDF.drawToFile(drawing, file_name)
  6546. else:
  6547. if orientation == 'p':
  6548. page_size = portrait(self.pagesize[p_size])
  6549. else:
  6550. page_size = landscape(self.pagesize[p_size])
  6551. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6552. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6553. renderPDF.draw(drawing, my_canvas, 0, 0)
  6554. my_canvas.save()
  6555. except Exception as e:
  6556. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6557. return 'fail'
  6558. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6559. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6560. """
  6561. Exports a Geometry Object to an SVG file.
  6562. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6563. :param filename: Path to the SVG file to save to.
  6564. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6565. :return:
  6566. """
  6567. self.defaults.report_usage("export_svg()")
  6568. if filename is None:
  6569. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6570. is not None else self.defaults["global_last_folder"]
  6571. self.log.debug("export_svg()")
  6572. try:
  6573. obj = self.collection.get_by_name(str(obj_name))
  6574. except Exception:
  6575. # TODO: The return behavior has not been established... should raise exception?
  6576. return "Could not retrieve object: %s" % obj_name
  6577. with self.proc_container.new(_("Exporting SVG")) as proc:
  6578. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6579. # Determine bounding area for svg export
  6580. bounds = obj.bounds()
  6581. size = obj.size()
  6582. # Convert everything to strings for use in the xml doc
  6583. svgwidth = str(size[0])
  6584. svgheight = str(size[1])
  6585. minx = str(bounds[0])
  6586. miny = str(bounds[1] - size[1])
  6587. uom = obj.units.lower()
  6588. # Add a SVG Header and footer to the svg output from shapely
  6589. # The transform flips the Y Axis so that everything renders
  6590. # properly within svg apps such as inkscape
  6591. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6592. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6593. svg_header += 'width="' + svgwidth + uom + '" '
  6594. svg_header += 'height="' + svgheight + uom + '" '
  6595. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6596. svg_header += '<g transform="scale(1,-1)">'
  6597. svg_footer = '</g> </svg>'
  6598. svg_elem = svg_header + exported_svg + svg_footer
  6599. # Parse the xml through a xml parser just to add line feeds
  6600. # and to make it look more pretty for the output
  6601. svgcode = parse_xml_string(svg_elem)
  6602. svgcode = svgcode.toprettyxml()
  6603. try:
  6604. with open(filename, 'w') as fp:
  6605. fp.write(svgcode)
  6606. except PermissionError:
  6607. self.inform.emit('[WARNING] %s' %
  6608. _("Permission denied, saving not possible.\n"
  6609. "Most likely another app is holding the file open and not accessible."))
  6610. return 'fail'
  6611. if self.defaults["global_open_style"] is False:
  6612. self.file_opened.emit("SVG", filename)
  6613. self.file_saved.emit("SVG", filename)
  6614. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6615. def save_source_file(self, obj_name, filename, use_thread=True):
  6616. """
  6617. Exports a FlatCAM Object to an Gerber/Excellon file.
  6618. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6619. :param filename: Path to the Gerber file to save to.
  6620. :param use_thread: if to be run in a separate thread
  6621. :return:
  6622. """
  6623. self.defaults.report_usage("save source file()")
  6624. if filename is None:
  6625. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6626. is not None else self.defaults["global_last_folder"]
  6627. self.log.debug("save source file()")
  6628. obj = self.collection.get_by_name(obj_name)
  6629. file_string = StringIO(obj.source_file)
  6630. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6631. if file_string.getvalue() == '':
  6632. self.inform.emit('[ERROR_NOTCL] %s' %
  6633. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6634. return 'fail'
  6635. try:
  6636. with open(filename, 'w') as file:
  6637. file.writelines('G04*\n')
  6638. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6639. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6640. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6641. file.writelines('G04 Created on : %s*\n' % time_string)
  6642. for line in file_string:
  6643. file.writelines(line)
  6644. except PermissionError:
  6645. self.inform.emit('[WARNING] %s' %
  6646. _("Permission denied, saving not possible.\n"
  6647. "Most likely another app is holding the file open and not accessible."))
  6648. return 'fail'
  6649. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6650. """
  6651. Exports a Excellon Object to an Excellon file.
  6652. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6653. :param filename: Path to the Excellon file to save to.
  6654. :param local_use:
  6655. :param use_thread: if to be run in a separate thread
  6656. :return:
  6657. """
  6658. self.defaults.report_usage("export_excellon()")
  6659. if filename is None:
  6660. if self.defaults["global_last_save_folder"]:
  6661. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6662. else:
  6663. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6664. self.log.debug("export_excellon()")
  6665. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6666. self.defaults["excellon_exp_decimals"]
  6667. )
  6668. if local_use is None:
  6669. try:
  6670. obj = self.collection.get_by_name(str(obj_name))
  6671. except Exception:
  6672. return "Could not retrieve object: %s" % obj_name
  6673. else:
  6674. obj = local_use
  6675. if not isinstance(obj, ExcellonObject):
  6676. self.inform.emit('[ERROR_NOTCL] %s' %
  6677. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6678. return
  6679. # updated units
  6680. eunits = self.defaults["excellon_exp_units"]
  6681. ewhole = self.defaults["excellon_exp_integer"]
  6682. efract = self.defaults["excellon_exp_decimals"]
  6683. ezeros = self.defaults["excellon_exp_zeros"]
  6684. eformat = self.defaults["excellon_exp_format"]
  6685. slot_type = self.defaults["excellon_exp_slot_type"]
  6686. fc_units = self.defaults['units'].upper()
  6687. if fc_units == 'MM':
  6688. factor = 1 if eunits == 'METRIC' else 0.03937
  6689. else:
  6690. factor = 25.4 if eunits == 'METRIC' else 1
  6691. def make_excellon():
  6692. try:
  6693. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6694. header = 'M48\n'
  6695. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6696. (str(self.version), str(self.version_date))
  6697. header += ';Filename: %s' % str(obj_name) + '\n'
  6698. header += ';Created on : %s' % time_str + '\n'
  6699. if eformat == 'dec':
  6700. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6701. header += eunits + '\n'
  6702. for tool in obj.tools:
  6703. if eunits == 'METRIC':
  6704. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6705. tool=str(tool),
  6706. dec=2)
  6707. else:
  6708. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6709. tool=str(tool),
  6710. dec=4)
  6711. else:
  6712. if ezeros == 'LZ':
  6713. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6714. form='ndec', e_zeros='LZ', factor=factor,
  6715. slot_type=slot_type)
  6716. header += '%s,%s\n' % (eunits, 'LZ')
  6717. header += format_exc
  6718. for tool in obj.tools:
  6719. if eunits == 'METRIC':
  6720. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6721. tool=str(tool),
  6722. dec=2)
  6723. else:
  6724. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6725. tool=str(tool),
  6726. dec=4)
  6727. else:
  6728. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6729. form='ndec', e_zeros='TZ', factor=factor,
  6730. slot_type=slot_type)
  6731. header += '%s,%s\n' % (eunits, 'TZ')
  6732. header += format_exc
  6733. for tool in obj.tools:
  6734. if eunits == 'METRIC':
  6735. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6736. tool=str(tool),
  6737. dec=2)
  6738. else:
  6739. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6740. tool=str(tool),
  6741. dec=4)
  6742. header += '%\n'
  6743. footer = 'M30\n'
  6744. exported_excellon = header
  6745. exported_excellon += excellon_code
  6746. exported_excellon += footer
  6747. if local_use is None:
  6748. try:
  6749. with open(filename, 'w') as fp:
  6750. fp.write(exported_excellon)
  6751. except PermissionError:
  6752. self.inform.emit('[WARNING] %s' %
  6753. _("Permission denied, saving not possible.\n"
  6754. "Most likely another app is holding the file open and not accessible."))
  6755. return 'fail'
  6756. if self.defaults["global_open_style"] is False:
  6757. self.file_opened.emit("Excellon", filename)
  6758. self.file_saved.emit("Excellon", filename)
  6759. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6760. else:
  6761. return exported_excellon
  6762. except Exception as e:
  6763. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6764. return 'fail'
  6765. if use_thread is True:
  6766. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6767. def job_thread_exc(app_obj):
  6768. ret = make_excellon()
  6769. if ret == 'fail':
  6770. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6771. return
  6772. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6773. else:
  6774. eret = make_excellon()
  6775. if eret == 'fail':
  6776. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6777. return 'fail'
  6778. if local_use is not None:
  6779. return eret
  6780. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6781. """
  6782. Exports a Gerber Object to an Gerber file.
  6783. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6784. :param filename: Path to the Gerber file to save to.
  6785. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6786. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6787. :param use_thread: if to be run in a separate thread
  6788. :return:
  6789. """
  6790. self.defaults.report_usage("export_gerber()")
  6791. if filename is None:
  6792. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6793. is not None else self.defaults["global_last_folder"]
  6794. self.log.debug("export_gerber()")
  6795. if local_use is None:
  6796. try:
  6797. obj = self.collection.get_by_name(str(obj_name))
  6798. except Exception:
  6799. return "Could not retrieve object: %s" % obj_name
  6800. else:
  6801. obj = local_use
  6802. # updated units
  6803. gunits = self.defaults["gerber_exp_units"]
  6804. gwhole = self.defaults["gerber_exp_integer"]
  6805. gfract = self.defaults["gerber_exp_decimals"]
  6806. gzeros = self.defaults["gerber_exp_zeros"]
  6807. fc_units = self.defaults['units'].upper()
  6808. if fc_units == 'MM':
  6809. factor = 1 if gunits == 'MM' else 0.03937
  6810. else:
  6811. factor = 25.4 if gunits == 'MM' else 1
  6812. def make_gerber():
  6813. try:
  6814. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6815. header = 'G04*\n'
  6816. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6817. (str(self.version), str(self.version_date))
  6818. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6819. header += 'G04 Created on : %s*' % time_str + '\n'
  6820. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6821. header += "%MO{units}*%\n".format(units=gunits)
  6822. for apid in obj.apertures:
  6823. if obj.apertures[apid]['type'] == 'C':
  6824. header += "%ADD{apid}{type},{size}*%\n".format(
  6825. apid=str(apid),
  6826. type='C',
  6827. size=(factor * obj.apertures[apid]['size'])
  6828. )
  6829. elif obj.apertures[apid]['type'] == 'R':
  6830. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6831. apid=str(apid),
  6832. type='R',
  6833. width=(factor * obj.apertures[apid]['width']),
  6834. height=(factor * obj.apertures[apid]['height'])
  6835. )
  6836. elif obj.apertures[apid]['type'] == 'O':
  6837. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6838. apid=str(apid),
  6839. type='O',
  6840. width=(factor * obj.apertures[apid]['width']),
  6841. height=(factor * obj.apertures[apid]['height'])
  6842. )
  6843. header += '\n'
  6844. # obsolete units but some software may need it
  6845. if gunits == 'IN':
  6846. header += 'G70*\n'
  6847. else:
  6848. header += 'G71*\n'
  6849. # Absolute Mode
  6850. header += 'G90*\n'
  6851. header += 'G01*\n'
  6852. # positive polarity
  6853. header += '%LPD*%\n'
  6854. footer = 'M02*\n'
  6855. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6856. exported_gerber = header
  6857. exported_gerber += gerber_code
  6858. exported_gerber += footer
  6859. if local_use is None:
  6860. try:
  6861. with open(filename, 'w') as fp:
  6862. fp.write(exported_gerber)
  6863. except PermissionError:
  6864. self.inform.emit('[WARNING] %s' %
  6865. _("Permission denied, saving not possible.\n"
  6866. "Most likely another app is holding the file open and not accessible."))
  6867. return 'fail'
  6868. if self.defaults["global_open_style"] is False:
  6869. self.file_opened.emit("Gerber", filename)
  6870. self.file_saved.emit("Gerber", filename)
  6871. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6872. else:
  6873. return exported_gerber
  6874. except Exception as e:
  6875. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6876. return 'fail'
  6877. if use_thread is True:
  6878. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6879. def job_thread_grb(app_obj):
  6880. ret = make_gerber()
  6881. if ret == 'fail':
  6882. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6883. return
  6884. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6885. else:
  6886. gret = make_gerber()
  6887. if gret == 'fail':
  6888. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6889. return 'fail'
  6890. if local_use is not None:
  6891. return gret
  6892. def export_dxf(self, obj_name, filename, use_thread=True):
  6893. """
  6894. Exports a Geometry Object to an DXF file.
  6895. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6896. :param filename: Path to the DXF file to save to.
  6897. :param use_thread: if to be run in a separate thread
  6898. :return:
  6899. """
  6900. self.defaults.report_usage("export_dxf()")
  6901. if filename is None:
  6902. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6903. is not None else self.defaults["global_last_folder"]
  6904. self.log.debug("export_dxf()")
  6905. try:
  6906. obj = self.collection.get_by_name(str(obj_name))
  6907. except Exception:
  6908. # TODO: The return behavior has not been established... should raise exception?
  6909. return "Could not retrieve object: %s" % obj_name
  6910. def make_dxf():
  6911. try:
  6912. dxf_code = obj.export_dxf()
  6913. dxf_code.saveas(filename)
  6914. if self.defaults["global_open_style"] is False:
  6915. self.file_opened.emit("DXF", filename)
  6916. self.file_saved.emit("DXF", filename)
  6917. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6918. except Exception:
  6919. return 'fail'
  6920. if use_thread is True:
  6921. with self.proc_container.new(_("Exporting DXF")) as proc:
  6922. def job_thread_exc(app_obj):
  6923. ret_dxf_val = make_dxf()
  6924. if ret_dxf_val == 'fail':
  6925. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6926. return
  6927. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6928. else:
  6929. ret = make_dxf()
  6930. if ret == 'fail':
  6931. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6932. return
  6933. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6934. """
  6935. Adds a new Geometry Object to the projects and populates
  6936. it with shapes extracted from the SVG file.
  6937. :param plot: If True then the resulting object will be plotted on canvas
  6938. :param filename: Path to the SVG file.
  6939. :param geo_type: Type of FlatCAM object that will be created from SVG
  6940. :param outname: The name given to the resulting FlatCAM object
  6941. :return:
  6942. """
  6943. self.defaults.report_usage("import_svg()")
  6944. log.debug("App.import_svg()")
  6945. obj_type = ""
  6946. if geo_type is None or geo_type == "geometry":
  6947. obj_type = "geometry"
  6948. elif geo_type == "gerber":
  6949. obj_type = "gerber"
  6950. else:
  6951. self.inform.emit('[ERROR_NOTCL] %s' %
  6952. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6953. return
  6954. units = self.defaults['units'].upper()
  6955. def obj_init(geo_obj, app_obj):
  6956. geo_obj.import_svg(filename, obj_type, units=units)
  6957. geo_obj.multigeo = False
  6958. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6959. with self.proc_container.new(_("Importing SVG")) as proc:
  6960. # Object name
  6961. name = outname or filename.split('/')[-1].split('\\')[-1]
  6962. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6963. if ret == 'fail':
  6964. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6965. return 'fail'
  6966. # Register recent file
  6967. self.file_opened.emit("svg", filename)
  6968. # appGUI feedback
  6969. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6970. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6971. """
  6972. Adds a new Geometry Object to the projects and populates
  6973. it with shapes extracted from the DXF file.
  6974. :param filename: Path to the DXF file.
  6975. :param geo_type: Type of FlatCAM object that will be created from DXF
  6976. :param outname: Name for the imported Geometry
  6977. :param plot: If True then the resulting object will be plotted on canvas
  6978. :return:
  6979. """
  6980. self.defaults.report_usage("import_dxf()")
  6981. obj_type = ""
  6982. if geo_type is None or geo_type == "geometry":
  6983. obj_type = "geometry"
  6984. elif geo_type == "gerber":
  6985. obj_type = geo_type
  6986. else:
  6987. self.inform.emit('[ERROR_NOTCL] %s' %
  6988. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6989. return
  6990. units = self.defaults['units'].upper()
  6991. def obj_init(geo_obj, app_obj):
  6992. geo_obj.import_dxf(filename, obj_type, units=units)
  6993. geo_obj.multigeo = False
  6994. with self.proc_container.new(_("Importing DXF")):
  6995. # Object name
  6996. name = outname or filename.split('/')[-1].split('\\')[-1]
  6997. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6998. if ret == 'fail':
  6999. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7000. return 'fail'
  7001. # Register recent file
  7002. self.file_opened.emit("dxf", filename)
  7003. # appGUI feedback
  7004. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7005. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7006. """
  7007. Opens a Gerber file, parses it and creates a new object for
  7008. it in the program. Thread-safe.
  7009. :param outname: Name of the resulting object. None causes the
  7010. name to be that of the file. Str.
  7011. :param filename: Gerber file filename
  7012. :type filename: str
  7013. :param plot: boolean, to plot or not the resulting object
  7014. :param from_tcl: True if run from Tcl Shell
  7015. :return: None
  7016. """
  7017. # How the object should be initialized
  7018. def obj_init(gerber_obj, app_obj):
  7019. assert isinstance(gerber_obj, GerberObject), \
  7020. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7021. # Opening the file happens here
  7022. try:
  7023. gerber_obj.parse_file(filename)
  7024. except IOError:
  7025. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7026. return "fail"
  7027. except ParseError as err:
  7028. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7029. app_obj.log.error(str(err))
  7030. return "fail"
  7031. except Exception as e:
  7032. log.debug("App.open_gerber() --> %s" % str(e))
  7033. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7034. msg += traceback.format_exc()
  7035. app_obj.inform.emit(msg)
  7036. return "fail"
  7037. if gerber_obj.is_empty():
  7038. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7039. _("Object is not Gerber file or empty. Aborting object creation."))
  7040. return "fail"
  7041. App.log.debug("open_gerber()")
  7042. with self.proc_container.new(_("Opening Gerber")):
  7043. # Object name
  7044. name = outname or filename.split('/')[-1].split('\\')[-1]
  7045. # # ## Object creation # ##
  7046. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7047. if ret_val == 'fail':
  7048. if from_tcl:
  7049. filename = self.defaults['global_tcl_path'] + '/' + name
  7050. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7051. if ret_val == 'fail':
  7052. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7053. return 'fail'
  7054. # Register recent file
  7055. self.file_opened.emit("gerber", filename)
  7056. # appGUI feedback
  7057. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7058. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7059. """
  7060. Opens an Excellon file, parses it and creates a new object for
  7061. it in the program. Thread-safe.
  7062. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7063. :param filename: Excellon file filename
  7064. :type filename: str
  7065. :param plot: boolean, to plot or not the resulting object
  7066. :param from_tcl: True if run from Tcl Shell
  7067. :return: None
  7068. """
  7069. App.log.debug("open_excellon()")
  7070. # How the object should be initialized
  7071. def obj_init(excellon_obj, app_obj):
  7072. try:
  7073. ret = excellon_obj.parse_file(filename=filename)
  7074. if ret == "fail":
  7075. log.debug("Excellon parsing failed.")
  7076. self.inform.emit('[ERROR_NOTCL] %s' %
  7077. _("This is not Excellon file."))
  7078. return "fail"
  7079. except IOError:
  7080. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7081. (_("Cannot open file"), filename))
  7082. log.debug("Could not open Excellon object.")
  7083. return "fail"
  7084. except Exception:
  7085. msg = '[ERROR_NOTCL] %s' % \
  7086. _("An internal error has occurred. See shell.\n")
  7087. msg += traceback.format_exc()
  7088. app_obj.inform.emit(msg)
  7089. return "fail"
  7090. ret = excellon_obj.create_geometry()
  7091. if ret == 'fail':
  7092. log.debug("Could not create geometry for Excellon object.")
  7093. return "fail"
  7094. for tool in excellon_obj.tools:
  7095. if excellon_obj.tools[tool]['solid_geometry']:
  7096. return
  7097. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7098. return "fail"
  7099. with self.proc_container.new(_("Opening Excellon.")):
  7100. # Object name
  7101. name = outname or filename.split('/')[-1].split('\\')[-1]
  7102. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7103. if ret_val == 'fail':
  7104. if from_tcl:
  7105. filename = self.defaults['global_tcl_path'] + '/' + name
  7106. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7107. if ret_val == 'fail':
  7108. self.inform.emit('[ERROR_NOTCL] %s' %
  7109. _('Open Excellon file failed. Probable not an Excellon file.'))
  7110. return
  7111. # Register recent file
  7112. self.file_opened.emit("excellon", filename)
  7113. # appGUI feedback
  7114. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7115. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7116. """
  7117. Opens a G-gcode file, parses it and creates a new object for
  7118. it in the program. Thread-safe.
  7119. :param filename: G-code file filename
  7120. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7121. :param force_parsing:
  7122. :param plot: If True plot the object on canvas
  7123. :param from_tcl: True if run from Tcl Shell
  7124. :return: None
  7125. """
  7126. App.log.debug("open_gcode()")
  7127. # How the object should be initialized
  7128. def obj_init(job_obj, app_obj_):
  7129. """
  7130. :param job_obj: the resulting object
  7131. :type app_obj_: App
  7132. """
  7133. assert isinstance(app_obj_, App), \
  7134. "Initializer expected App, got %s" % type(app_obj_)
  7135. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7136. try:
  7137. f = open(filename)
  7138. gcode = f.read()
  7139. f.close()
  7140. except IOError:
  7141. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7142. return "fail"
  7143. job_obj.gcode = gcode
  7144. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7145. if gcode_ret == "fail":
  7146. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7147. return "fail"
  7148. job_obj.create_geometry()
  7149. with self.proc_container.new(_("Opening G-Code.")):
  7150. # Object name
  7151. name = outname or filename.split('/')[-1].split('\\')[-1]
  7152. # New object creation and file processing
  7153. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7154. if ret_val == 'fail':
  7155. if from_tcl:
  7156. filename = self.defaults['global_tcl_path'] + '/' + name
  7157. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7158. if ret_val == 'fail':
  7159. self.inform.emit('[ERROR_NOTCL] %s' %
  7160. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7161. "Try to load it from File menu.\n "
  7162. "Attempting to create a FlatCAM CNCJob Object from "
  7163. "G-Code file failed during processing"))
  7164. return "fail"
  7165. # Register recent file
  7166. self.file_opened.emit("cncjob", filename)
  7167. # appGUI feedback
  7168. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7169. def open_hpgl2(self, filename, outname=None):
  7170. """
  7171. Opens a HPGL2 file, parses it and creates a new object for
  7172. it in the program. Thread-safe.
  7173. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7174. :param filename: HPGL2 file filename
  7175. :return: None
  7176. """
  7177. filename = filename
  7178. # How the object should be initialized
  7179. def obj_init(geo_obj, app_obj):
  7180. assert isinstance(geo_obj, GeometryObject), \
  7181. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7182. # Opening the file happens here
  7183. obj = HPGL2(self)
  7184. try:
  7185. HPGL2.parse_file(obj, filename)
  7186. except IOError:
  7187. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7188. return "fail"
  7189. except ParseError as err:
  7190. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7191. app_obj.log.error(str(err))
  7192. return "fail"
  7193. except Exception as e:
  7194. log.debug("App.open_hpgl2() --> %s" % str(e))
  7195. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7196. msg += traceback.format_exc()
  7197. app_obj.inform.emit(msg)
  7198. return "fail"
  7199. geo_obj.multigeo = True
  7200. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7201. geo_obj.tools = deepcopy(obj.tools)
  7202. geo_obj.source_file = deepcopy(obj.source_file)
  7203. del obj
  7204. if not geo_obj.solid_geometry:
  7205. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7206. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7207. return "fail"
  7208. App.log.debug("open_hpgl2()")
  7209. with self.proc_container.new(_("Opening HPGL2")):
  7210. # Object name
  7211. name = outname or filename.split('/')[-1].split('\\')[-1]
  7212. # # ## Object creation # ##
  7213. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7214. if ret == 'fail':
  7215. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7216. return 'fail'
  7217. # Register recent file
  7218. self.file_opened.emit("geometry", filename)
  7219. # appGUI feedback
  7220. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7221. def open_script(self, filename, outname=None, silent=False):
  7222. """
  7223. Opens a Script file, parses it and creates a new object for
  7224. it in the program. Thread-safe.
  7225. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7226. :param filename: Script file filename
  7227. :param silent: If True there will be no messages printed to StatusBar
  7228. :return: None
  7229. """
  7230. def obj_init(script_obj, app_obj):
  7231. assert isinstance(script_obj, ScriptObject), \
  7232. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7233. if silent is False:
  7234. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7235. try:
  7236. script_obj.parse_file(filename)
  7237. except IOError:
  7238. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7239. return "fail"
  7240. except ParseError as err:
  7241. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7242. app_obj.log.error(str(err))
  7243. return "fail"
  7244. except Exception as e:
  7245. log.debug("App.open_script() -> %s" % str(e))
  7246. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7247. msg += traceback.format_exc()
  7248. app_obj.inform.emit(msg)
  7249. return "fail"
  7250. App.log.debug("open_script()")
  7251. with self.proc_container.new(_("Opening TCL Script...")):
  7252. # Object name
  7253. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7254. # Object creation
  7255. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7256. if ret_val == 'fail':
  7257. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7258. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7259. if ret_val == 'fail':
  7260. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7261. return 'fail'
  7262. # Register recent file
  7263. self.file_opened.emit("script", filename)
  7264. # appGUI feedback
  7265. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7266. def open_config_file(self, filename, run_from_arg=None):
  7267. """
  7268. Loads a config file from the specified file.
  7269. :param filename: Name of the file from which to load.
  7270. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7271. :return: None
  7272. """
  7273. App.log.debug("Opening config file: " + filename)
  7274. if run_from_arg:
  7275. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7276. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7277. _("Opening FlatCAM Config file.")),
  7278. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7279. color=QtGui.QColor("gray"))
  7280. # # add the tab if it was closed
  7281. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7282. # # first clear previous text in text editor (if any)
  7283. # self.ui.text_editor_tab.code_editor.clear()
  7284. #
  7285. # # Switch plot_area to CNCJob tab
  7286. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7287. # close the Code editor if already open
  7288. if self.toggle_codeeditor:
  7289. self.on_toggle_code_editor()
  7290. self.on_toggle_code_editor()
  7291. try:
  7292. if filename:
  7293. f = QtCore.QFile(filename)
  7294. if f.open(QtCore.QIODevice.ReadOnly):
  7295. stream = QtCore.QTextStream(f)
  7296. code_edited = stream.readAll()
  7297. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7298. f.close()
  7299. except IOError:
  7300. App.log.error("Failed to open config file: %s" % filename)
  7301. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7302. (_("Failed to open config file"), filename))
  7303. return
  7304. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7305. """
  7306. Loads a project from the specified file.
  7307. 1) Loads and parses file
  7308. 2) Registers the file as recently opened.
  7309. 3) Calls on_file_new()
  7310. 4) Updates options
  7311. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7312. 6) Calls plot_all() if plot=True
  7313. :param filename: Name of the file from which to load.
  7314. :param run_from_arg: True if run for arguments
  7315. :param plot: If True plot all objects in the project
  7316. :param cli: Run from command line
  7317. :param from_tcl: True if run from Tcl Sehll
  7318. :return: None
  7319. """
  7320. App.log.debug("Opening project: " + filename)
  7321. # block autosaving while a project is loaded
  7322. self.block_autosave = True
  7323. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7324. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7325. if cli is None:
  7326. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7327. if run_from_arg:
  7328. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7329. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7330. _("Opening FlatCAM Project file.")),
  7331. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7332. color=QtGui.QColor("gray"))
  7333. # Open and parse an uncompressed Project file
  7334. try:
  7335. f = open(filename, 'r')
  7336. except IOError:
  7337. if from_tcl:
  7338. name = filename.split('/')[-1].split('\\')[-1]
  7339. filename = self.defaults['global_tcl_path'] + '/' + name
  7340. try:
  7341. f = open(filename, 'r')
  7342. except IOError:
  7343. log.error("Failed to open project file: %s" % filename)
  7344. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7345. return
  7346. else:
  7347. log.error("Failed to open project file: %s" % filename)
  7348. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7349. return
  7350. try:
  7351. d = json.load(f, object_hook=dict2obj)
  7352. except Exception as e:
  7353. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7354. (filename, str(e)))
  7355. f.close()
  7356. # Open and parse a compressed Project file
  7357. try:
  7358. with lzma.open(filename) as f:
  7359. file_content = f.read().decode('utf-8')
  7360. d = json.loads(file_content, object_hook=dict2obj)
  7361. except Exception as e:
  7362. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7363. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7364. return
  7365. # Clear the current project
  7366. # # NOT THREAD SAFE # ##
  7367. if run_from_arg is True:
  7368. pass
  7369. elif cli is True:
  7370. self.delete_selection_shape()
  7371. else:
  7372. self.on_file_new()
  7373. # Project options
  7374. self.options.update(d['options'])
  7375. self.project_filename = filename
  7376. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7377. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7378. if cli is None:
  7379. self.set_screen_units(self.options["units"])
  7380. # Re create objects
  7381. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7382. for obj in d['objs']:
  7383. try:
  7384. def obj_init(obj_inst, app_inst):
  7385. obj_inst.from_dict(obj)
  7386. App.log.debug("Recreating from opened project an %s object: %s" %
  7387. (obj['kind'].capitalize(), obj['options']['name']))
  7388. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7389. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7390. if cli is None:
  7391. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7392. obj['kind'].upper(),
  7393. obj['options']['name']
  7394. )
  7395. )
  7396. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7397. except Exception as e:
  7398. print('App.open_project() --> ' + str(e))
  7399. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7400. self.should_we_save = False
  7401. self.file_opened.emit("project", filename)
  7402. # restore autosaving after a project was loaded
  7403. self.block_autosave = False
  7404. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7405. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7406. if cli is None:
  7407. self.set_ui_title(name=self.project_filename)
  7408. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7409. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7410. """
  7411. Re-generates all plots from all objects.
  7412. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7413. :param muted: if True don't print messages
  7414. :param use_thread: if True will use threading for plotting the objects
  7415. :return: None
  7416. """
  7417. self.log.debug("Plot_all()")
  7418. if muted is not True:
  7419. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7420. for plot_obj in self.collection.get_list():
  7421. def worker_task(obj):
  7422. with self.proc_container.new("Plotting"):
  7423. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7424. if fit_view is True:
  7425. self.app_obj.object_plotted.emit(obj)
  7426. if use_thread is True:
  7427. # Send to worker
  7428. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7429. else:
  7430. worker_task(plot_obj)
  7431. def register_folder(self, filename):
  7432. """
  7433. Register the last folder used by the app to open something
  7434. :param filename: the last folder is extracted from the filename
  7435. :return: None
  7436. """
  7437. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7438. def register_save_folder(self, filename):
  7439. """
  7440. Register the last folder used by the app to save something
  7441. :param filename: the last folder is extracted from the filename
  7442. :return: None
  7443. """
  7444. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7445. # def set_progress_bar(self, percentage, text=""):
  7446. # """
  7447. # Set a progress bar to a value (percentage)
  7448. #
  7449. # :param percentage: Value set to the progressbar
  7450. # :param text: Not used
  7451. # :return: None
  7452. # """
  7453. # self.ui.progress_bar.setValue(int(percentage))
  7454. def setup_recent_items(self):
  7455. """
  7456. Setup a dictionary with the recent files accessed, organized by type
  7457. :return:
  7458. """
  7459. icons = {
  7460. "gerber": self.resource_location + "/flatcam_icon16.png",
  7461. "excellon": self.resource_location + "/drill16.png",
  7462. 'geometry': self.resource_location + "/geometry16.png",
  7463. "cncjob": self.resource_location + "/cnc16.png",
  7464. "script": self.resource_location + "/script_new24.png",
  7465. "document": self.resource_location + "/notes16_1.png",
  7466. "project": self.resource_location + "/project16.png",
  7467. "svg": self.resource_location + "/geometry16.png",
  7468. "dxf": self.resource_location + "/dxf16.png",
  7469. "pdf": self.resource_location + "/pdf32.png",
  7470. "image": self.resource_location + "/image16.png"
  7471. }
  7472. try:
  7473. image_opener = self.image_tool.import_image
  7474. except AttributeError:
  7475. image_opener = None
  7476. openers = {
  7477. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7478. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7479. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7480. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7481. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7482. "document": None,
  7483. 'project': self.open_project,
  7484. 'svg': self.import_svg,
  7485. 'dxf': self.import_dxf,
  7486. 'image': image_opener,
  7487. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7488. }
  7489. # Open recent file for files
  7490. try:
  7491. f = open(self.data_path + '/recent.json')
  7492. except IOError:
  7493. App.log.error("Failed to load recent item list.")
  7494. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7495. return
  7496. try:
  7497. self.recent = json.load(f)
  7498. except json.errors.JSONDecodeError:
  7499. App.log.error("Failed to parse recent item list.")
  7500. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7501. f.close()
  7502. return
  7503. f.close()
  7504. # Open recent file for projects
  7505. try:
  7506. fp = open(self.data_path + '/recent_projects.json')
  7507. except IOError:
  7508. App.log.error("Failed to load recent project item list.")
  7509. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7510. return
  7511. try:
  7512. self.recent_projects = json.load(fp)
  7513. except json.errors.JSONDecodeError:
  7514. App.log.error("Failed to parse recent project item list.")
  7515. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7516. fp.close()
  7517. return
  7518. fp.close()
  7519. # Closure needed to create callbacks in a loop.
  7520. # Otherwise late binding occurs.
  7521. def make_callback(func, fname):
  7522. def opener():
  7523. func(fname)
  7524. return opener
  7525. def reset_recent_files():
  7526. # Reset menu
  7527. self.ui.recent.clear()
  7528. self.recent = []
  7529. try:
  7530. ff = open(self.data_path + '/recent.json', 'w')
  7531. except IOError:
  7532. App.log.error("Failed to open recent items file for writing.")
  7533. return
  7534. json.dump(self.recent, ff)
  7535. def reset_recent_projects():
  7536. # Reset menu
  7537. self.ui.recent_projects.clear()
  7538. self.recent_projects = []
  7539. try:
  7540. frp = open(self.data_path + '/recent_projects.json', 'w')
  7541. except IOError:
  7542. App.log.error("Failed to open recent projects items file for writing.")
  7543. return
  7544. json.dump(self.recent, frp)
  7545. # Reset menu
  7546. self.ui.recent.clear()
  7547. self.ui.recent_projects.clear()
  7548. # Create menu items for projects
  7549. for recent in self.recent_projects:
  7550. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7551. if recent['kind'] == 'project':
  7552. try:
  7553. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7554. # Attach callback
  7555. o = make_callback(openers[recent["kind"]], recent['filename'])
  7556. action.triggered.connect(o)
  7557. self.ui.recent_projects.addAction(action)
  7558. except KeyError:
  7559. App.log.error("Unsupported file type: %s" % recent["kind"])
  7560. # Last action in Recent Files menu is one that Clear the content
  7561. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7562. (_("Clear Recent projects")), self)
  7563. clear_action_proj.triggered.connect(reset_recent_projects)
  7564. self.ui.recent_projects.addSeparator()
  7565. self.ui.recent_projects.addAction(clear_action_proj)
  7566. # Create menu items for files
  7567. for recent in self.recent:
  7568. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7569. if recent['kind'] != 'project':
  7570. try:
  7571. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7572. # Attach callback
  7573. o = make_callback(openers[recent["kind"]], recent['filename'])
  7574. action.triggered.connect(o)
  7575. self.ui.recent.addAction(action)
  7576. except KeyError:
  7577. App.log.error("Unsupported file type: %s" % recent["kind"])
  7578. # Last action in Recent Files menu is one that Clear the content
  7579. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7580. (_("Clear Recent files")), self)
  7581. clear_action.triggered.connect(reset_recent_files)
  7582. self.ui.recent.addSeparator()
  7583. self.ui.recent.addAction(clear_action)
  7584. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7585. # self.ui.menufilerecent.set_submenu(recent_menu)
  7586. # recent_menu.show_all()
  7587. # self.ui.recent.show()
  7588. self.log.debug("Recent items list has been populated.")
  7589. def setup_component_editor(self):
  7590. """
  7591. Default text for the Selected tab when is not taken by the Object UI.
  7592. :return:
  7593. """
  7594. # label = QtWidgets.QLabel("Choose an item from Project")
  7595. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7596. sel_title = QtWidgets.QTextEdit(
  7597. _('<b>Shortcut Key List</b>'))
  7598. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7599. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7600. f_settings = QSettings("Open Source", "FlatCAM")
  7601. if f_settings.contains("notebook_font_size"):
  7602. fsize = f_settings.value('notebook_font_size', type=int)
  7603. else:
  7604. fsize = 12
  7605. tsize = fsize + int(fsize / 2)
  7606. # selected_text = (_('''
  7607. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7608. # </p>
  7609. #
  7610. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7611. # The normal flow when working in FlatCAM is the following:</span></p>
  7612. #
  7613. # <ol>
  7614. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7615. # file into
  7616. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7617. # even dragging and dropping the files on the appGUI.<br />
  7618. # <br />
  7619. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7620. # drop of the
  7621. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7622. # &nbsp;</li>
  7623. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7624. # and then
  7625. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7626. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7627. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7628. # <br />
  7629. # If the selection of the object is done on the canvas by single click instead, and the
  7630. # <strong>SELECTED TAB</strong>
  7631. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7632. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7633. # it even if it was out of focus.<br />
  7634. # <br />
  7635. # You can change the parameters in this screen and the flow direction is like this:<br />
  7636. # <br />
  7637. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7638. # <strong> Geometry Object
  7639. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7640. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7641. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7642. # </ol>
  7643. #
  7644. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7645. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7646. # <strong>F3</strong>.</span></p>
  7647. #
  7648. # ''').format(fsize=fsize, tsize=tsize))
  7649. selected_text = '''
  7650. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7651. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7652. {s1}</span></p>
  7653. <ol>
  7654. <li><span style="font-size:{fsize}px">{s2}<br />
  7655. <br />
  7656. {s3}</span><br />
  7657. &nbsp;</li>
  7658. <li><span style="font-size:{fsize}px">{s4}<br />
  7659. &nbsp;</li>
  7660. <br />
  7661. <li><span style="font-size:{fsize}px">{s5}<br />
  7662. &nbsp;</li>
  7663. <br />
  7664. <li><span style="font-size:{fsize}px">{s6}<br />
  7665. <br />
  7666. {s7}</span></li>
  7667. </ol>
  7668. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7669. '''.format(
  7670. title=_("Selected Tab - Choose an Item from Project Tab"),
  7671. subtitle=_("Details"),
  7672. s1=_("The normal flow when working with the application is the following:"),
  7673. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7674. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7675. "files on the GUI."),
  7676. s3=_("You can also load a project by double clicking on the project file, "
  7677. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7678. "actions offered within the app."),
  7679. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7680. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7681. "SELECTED TAB will be updated with the object properties according to its kind: "
  7682. "Gerber, Excellon, Geometry or CNCJob object."),
  7683. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7684. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7685. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7686. "the SELECTED TAB and populate it even if it was out of focus."),
  7687. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7688. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7689. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7690. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7691. "(again, done in SELECTED TAB) --> Save GCode."),
  7692. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7693. "or through its own key shortcut: <b>F3</b>."),
  7694. tsize=tsize,
  7695. fsize=fsize
  7696. )
  7697. sel_title.setText(selected_text)
  7698. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7699. self.ui.selected_scroll_area.setWidget(sel_title)
  7700. def setup_obj_classes(self):
  7701. """
  7702. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7703. class.
  7704. :return: None
  7705. """
  7706. FlatCAMObj.app = self
  7707. ObjectCollection.app = self
  7708. Gerber.app = self
  7709. Excellon.app = self
  7710. Geometry.app = self
  7711. CNCjob.app = self
  7712. FCProcess.app = self
  7713. FCProcessContainer.app = self
  7714. OptionsGroupUI.app = self
  7715. def version_check(self):
  7716. """
  7717. Checks for the latest version of the program. Alerts the
  7718. user if theirs is outdated. This method is meant to be run
  7719. in a separate thread.
  7720. :return: None
  7721. """
  7722. self.log.debug("version_check()")
  7723. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7724. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7725. App.version_url,
  7726. str(self.defaults['global_serial']),
  7727. str(self.version),
  7728. str(self.os),
  7729. urllib.parse.urlencode(self.defaults["global_stats"])
  7730. )
  7731. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7732. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7733. # urllib.parse.urlencode(self.defaults["global_stats"])
  7734. else:
  7735. # no_stats dict; just so it won't break things on website
  7736. no_ststs_dict = {}
  7737. no_ststs_dict["global_ststs"] = {}
  7738. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7739. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7740. App.log.debug("Checking for updates @ %s" % full_url)
  7741. # ## Get the data
  7742. try:
  7743. f = urllib.request.urlopen(full_url)
  7744. except Exception:
  7745. # App.log.warning("Failed checking for latest version. Could not connect.")
  7746. self.log.warning("Failed checking for latest version. Could not connect.")
  7747. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7748. return
  7749. try:
  7750. data = json.load(f)
  7751. except Exception as e:
  7752. App.log.error("Could not parse information about latest version.")
  7753. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7754. App.log.debug("json.load(): %s" % str(e))
  7755. f.close()
  7756. return
  7757. f.close()
  7758. # ## Latest version?
  7759. if self.version >= data["version"]:
  7760. App.log.debug("FlatCAM is up to date!")
  7761. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7762. return
  7763. App.log.debug("Newer version available.")
  7764. self.message.emit(
  7765. _("Newer Version Available"),
  7766. '%s<br><br>><b>%s</b><br>%s' % (
  7767. _("There is a newer version of FlatCAM available for download:"),
  7768. str(data["name"]),
  7769. str(data["message"])
  7770. ),
  7771. _("info")
  7772. )
  7773. def on_plotcanvas_setup(self, container=None):
  7774. """
  7775. This is doing the setup for the plot area (canvas).
  7776. :param container: QT Widget where to install the canvas
  7777. :return: None
  7778. """
  7779. if container:
  7780. plot_container = container
  7781. else:
  7782. plot_container = self.ui.right_layout
  7783. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7784. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7785. self.is_legacy = True
  7786. self.defaults["global_graphic_engine"] = "2D"
  7787. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7788. else:
  7789. try:
  7790. self.plotcanvas = PlotCanvas(plot_container, self)
  7791. except Exception as er:
  7792. msg_txt = traceback.format_exc()
  7793. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7794. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7795. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7796. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7797. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7798. msg += msg_txt
  7799. self.inform.emit(msg)
  7800. return 'fail'
  7801. # So it can receive key presses
  7802. self.plotcanvas.native.setFocus()
  7803. if self.is_legacy is False:
  7804. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7805. # Set the mouse button for panning
  7806. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7807. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7808. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7809. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7810. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7811. # Keys over plot enabled
  7812. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7813. if self.defaults['global_cursor_type'] == 'small':
  7814. self.app_cursor = self.plotcanvas.new_cursor()
  7815. else:
  7816. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7817. if self.ui.grid_snap_btn.isChecked():
  7818. self.app_cursor.enabled = True
  7819. else:
  7820. self.app_cursor.enabled = False
  7821. if self.is_legacy is False:
  7822. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7823. else:
  7824. # will use the default Matplotlib axes
  7825. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7826. def on_zoom_fit(self):
  7827. """
  7828. Callback for zoom-fit request. This can be either from the corresponding
  7829. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7830. with axes limits from the geometry bounds of all objects.
  7831. :return: None
  7832. """
  7833. if self.is_legacy is False:
  7834. self.plotcanvas.fit_view()
  7835. else:
  7836. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7837. width = xmax - xmin
  7838. height = ymax - ymin
  7839. xmin -= 0.05 * width
  7840. xmax += 0.05 * width
  7841. ymin -= 0.05 * height
  7842. ymax += 0.05 * height
  7843. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7844. def on_zoom_in(self):
  7845. """
  7846. Callback for zoom-in request.
  7847. :return:
  7848. """
  7849. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7850. def on_zoom_out(self):
  7851. """
  7852. Callback for zoom-out request.
  7853. :return:
  7854. """
  7855. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7856. def disable_all_plots(self):
  7857. self.defaults.report_usage("disable_all_plots()")
  7858. self.disable_plots(self.collection.get_list())
  7859. self.inform.emit('[success] %s' %
  7860. _("All plots disabled."))
  7861. def disable_other_plots(self):
  7862. self.defaults.report_usage("disable_other_plots()")
  7863. self.disable_plots(self.collection.get_non_selected())
  7864. self.inform.emit('[success] %s' %
  7865. _("All non selected plots disabled."))
  7866. def enable_all_plots(self):
  7867. self.defaults.report_usage("enable_all_plots()")
  7868. self.enable_plots(self.collection.get_list())
  7869. self.inform.emit('[success] %s' %
  7870. _("All plots enabled."))
  7871. def on_enable_sel_plots(self):
  7872. log.debug("App.on_enable_sel_plot()")
  7873. object_list = self.collection.get_selected()
  7874. self.enable_plots(objects=object_list)
  7875. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7876. def on_disable_sel_plots(self):
  7877. log.debug("App.on_disable_sel_plot()")
  7878. # self.inform.emit(_("Disabling plots ..."))
  7879. object_list = self.collection.get_selected()
  7880. self.disable_plots(objects=object_list)
  7881. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7882. def enable_plots(self, objects):
  7883. """
  7884. Enable plots
  7885. :param objects: list of Objects to be enabled
  7886. :return:
  7887. """
  7888. log.debug("Enabling plots ...")
  7889. # self.inform.emit(_("Working ..."))
  7890. for obj in objects:
  7891. if obj.options['plot'] is False:
  7892. obj.options.set_change_callback(lambda x: None)
  7893. obj.options['plot'] = True
  7894. try:
  7895. # only the Gerber obj has on_plot_cb_click() method
  7896. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7897. # disable this cb while disconnected,
  7898. # in case the operation takes time the user is not allowed to change it
  7899. obj.ui.plot_cb.setDisabled(True)
  7900. except AttributeError:
  7901. pass
  7902. obj.set_form_item("plot")
  7903. try:
  7904. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7905. obj.ui.plot_cb.setDisabled(False)
  7906. except AttributeError:
  7907. pass
  7908. obj.options.set_change_callback(obj.on_options_change)
  7909. def worker_task(objs):
  7910. with self.proc_container.new(_("Enabling plots ...")):
  7911. for plot_obj in objs:
  7912. # obj.options['plot'] = True
  7913. if isinstance(plot_obj, CNCJobObject):
  7914. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7915. else:
  7916. plot_obj.plot(visible=True)
  7917. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7918. def disable_plots(self, objects):
  7919. """
  7920. Disables plots
  7921. :param objects: list of Objects to be disabled
  7922. :return:
  7923. """
  7924. # if no objects selected then do nothing
  7925. if not self.collection.get_selected():
  7926. return
  7927. log.debug("Disabling plots ...")
  7928. # self.inform.emit(_("Working ..."))
  7929. for obj in objects:
  7930. if obj.options['plot'] is True:
  7931. obj.options.set_change_callback(lambda x: None)
  7932. obj.options['plot'] = False
  7933. try:
  7934. # only the Gerber obj has on_plot_cb_click() method
  7935. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7936. obj.ui.plot_cb.setDisabled(True)
  7937. except AttributeError:
  7938. pass
  7939. obj.set_form_item("plot")
  7940. try:
  7941. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7942. obj.ui.plot_cb.setDisabled(False)
  7943. except AttributeError:
  7944. pass
  7945. obj.options.set_change_callback(obj.on_options_change)
  7946. try:
  7947. self.delete_selection_shape()
  7948. except Exception as e:
  7949. log.debug("App.disable_plots() --> %s" % str(e))
  7950. def worker_task(objs):
  7951. with self.proc_container.new(_("Disabling plots ...")):
  7952. for plot_obj in objs:
  7953. # obj.options['plot'] = True
  7954. if isinstance(plot_obj, CNCJobObject):
  7955. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7956. else:
  7957. plot_obj.plot(visible=False)
  7958. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7959. def toggle_plots(self, objects):
  7960. """
  7961. Toggle plots visibility
  7962. :param objects: list of Objects for which to be toggled the visibility
  7963. :return: None
  7964. """
  7965. # if no objects selected then do nothing
  7966. if not self.collection.get_selected():
  7967. return
  7968. log.debug("Toggling plots ...")
  7969. self.inform.emit(_("Working ..."))
  7970. for obj in objects:
  7971. if obj.options['plot'] is False:
  7972. obj.options['plot'] = True
  7973. else:
  7974. obj.options['plot'] = False
  7975. self.app_obj.plots_updated.emit()
  7976. def clear_plots(self):
  7977. """
  7978. Clear the plots
  7979. :return: None
  7980. """
  7981. objects = self.collection.get_list()
  7982. for obj in objects:
  7983. obj.clear(obj == objects[-1])
  7984. # Clear pool to free memory
  7985. self.clear_pool()
  7986. def on_set_color_action_triggered(self):
  7987. """
  7988. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7989. :return:
  7990. """
  7991. new_color = self.defaults['gerber_plot_fill']
  7992. clicked_action = self.sender()
  7993. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7994. act_name = clicked_action.text()
  7995. sel_obj_list = self.collection.get_selected()
  7996. if not sel_obj_list:
  7997. return
  7998. # a default value, I just chose this one
  7999. alpha_level = 'BF'
  8000. for sel_obj in sel_obj_list:
  8001. if sel_obj.kind == 'excellon':
  8002. alpha_level = str(hex(
  8003. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8004. elif sel_obj.kind == 'gerber':
  8005. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8006. elif sel_obj.kind == 'geometry':
  8007. alpha_level = 'FF'
  8008. else:
  8009. log.debug(
  8010. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8011. continue
  8012. sel_obj.alpha_level = alpha_level
  8013. if act_name == _('Red'):
  8014. new_color = '#FF0000' + alpha_level
  8015. if act_name == _('Blue'):
  8016. new_color = '#0000FF' + alpha_level
  8017. if act_name == _('Yellow'):
  8018. new_color = '#FFDF00' + alpha_level
  8019. if act_name == _('Green'):
  8020. new_color = '#00FF00' + alpha_level
  8021. if act_name == _('Purple'):
  8022. new_color = '#FF00FF' + alpha_level
  8023. if act_name == _('Brown'):
  8024. new_color = '#A52A2A' + alpha_level
  8025. if act_name == _('White'):
  8026. new_color = '#FFFFFF' + alpha_level
  8027. if act_name == _('Black'):
  8028. new_color = '#000000' + alpha_level
  8029. if act_name == _('Custom'):
  8030. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8031. c_dialog = QtWidgets.QColorDialog()
  8032. plot_fill_color = c_dialog.getColor(initial=new_color)
  8033. if plot_fill_color.isValid() is False:
  8034. return
  8035. new_color = str(plot_fill_color.name()) + alpha_level
  8036. if act_name == _("Default"):
  8037. for sel_obj in sel_obj_list:
  8038. if sel_obj.kind == 'excellon':
  8039. new_color = self.defaults['excellon_plot_fill']
  8040. new_line_color = self.defaults['excellon_plot_line']
  8041. elif sel_obj.kind == 'gerber':
  8042. new_color = self.defaults['gerber_plot_fill']
  8043. new_line_color = self.defaults['gerber_plot_line']
  8044. elif sel_obj.kind == 'geometry':
  8045. new_color = self.defaults['geometry_plot_line']
  8046. new_line_color = self.defaults['geometry_plot_line']
  8047. else:
  8048. log.debug(
  8049. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8050. continue
  8051. sel_obj.fill_color = new_color
  8052. sel_obj.outline_color = new_line_color
  8053. sel_obj.shapes.redraw(
  8054. update_colors=(new_color, new_line_color)
  8055. )
  8056. return
  8057. if act_name == _("Opacity"):
  8058. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8059. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8060. if ok_button:
  8061. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8062. for sel_obj in sel_obj_list:
  8063. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8064. sel_obj.shapes.redraw(
  8065. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8066. )
  8067. return
  8068. new_line_color = color_variant(new_color[:7], 0.7)
  8069. if act_name == _("White"):
  8070. new_line_color = color_variant("#dedede", 0.7)
  8071. for sel_obj in sel_obj_list:
  8072. sel_obj.fill_color = new_color
  8073. sel_obj.outline_color = new_line_color
  8074. sel_obj.shapes.redraw(
  8075. update_colors=(new_color, new_line_color)
  8076. )
  8077. def generate_cnc_job(self, objects):
  8078. """
  8079. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8080. :param objects: Selected objects in the Project Tab
  8081. :return:
  8082. """
  8083. self.defaults.report_usage("generate_cnc_job()")
  8084. # for obj in objects:
  8085. # obj.generatecncjob()
  8086. for obj in objects:
  8087. obj.on_generatecnc_button_click()
  8088. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8089. """
  8090. Saves the current project to the specified file.
  8091. :param filename: Name of the file in which to save.
  8092. :type filename: str
  8093. :param quit_action: if the project saving will be followed by an app quit; boolean
  8094. :param silent: if True will not display status messages
  8095. :param from_tcl True is run from Tcl Shell
  8096. :return: None
  8097. """
  8098. self.log.debug("save_project()")
  8099. self.save_in_progress = True
  8100. with self.proc_container.new(_("Saving FlatCAM Project")):
  8101. # Capture the latest changes
  8102. # Current object
  8103. try:
  8104. current_object = self.collection.get_active()
  8105. if current_object:
  8106. current_object.read_form()
  8107. except Exception as e:
  8108. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8109. pass
  8110. # Serialize the whole project
  8111. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8112. "options": self.options,
  8113. "version": self.version}
  8114. if self.defaults["global_save_compressed"] is True:
  8115. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8116. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8117. # # Write
  8118. f.write(g)
  8119. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8120. else:
  8121. # Open file
  8122. try:
  8123. f = open(filename, 'w')
  8124. except IOError:
  8125. App.log.error("Failed to open file for saving: %s", filename)
  8126. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8127. return
  8128. # Write
  8129. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8130. f.close()
  8131. # verification of the saved project
  8132. # Open and parse
  8133. try:
  8134. saved_f = open(filename, 'r')
  8135. except IOError:
  8136. if silent is False:
  8137. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8138. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8139. return
  8140. try:
  8141. saved_d = json.load(saved_f, object_hook=dict2obj)
  8142. except Exception:
  8143. if silent is False:
  8144. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8145. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8146. f.close()
  8147. return
  8148. saved_f.close()
  8149. if silent is False:
  8150. if 'version' in saved_d:
  8151. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8152. else:
  8153. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8154. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8155. tb_settings = QSettings("Open Source", "FlatCAM")
  8156. lock_state = self.ui.lock_action.isChecked()
  8157. tb_settings.setValue('toolbar_lock', lock_state)
  8158. # This will write the setting to the platform specific storage.
  8159. del tb_settings
  8160. # if quit:
  8161. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8162. # t.start()
  8163. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8164. def start_delayed_quit(self, delay, filename, should_quit=None):
  8165. """
  8166. :param delay: period of checking if project file size is more than zero; in seconds
  8167. :param filename: the name of the project file to be checked periodically for size more than zero
  8168. :param should_quit: if the task finished will be followed by an app quit; boolean
  8169. :return:
  8170. """
  8171. to_quit = should_quit
  8172. self.save_timer = QtCore.QTimer()
  8173. self.save_timer.setInterval(delay)
  8174. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8175. self.save_timer.start()
  8176. def check_project_file_size(self, filename, should_quit=None):
  8177. """
  8178. :param filename: the name of the project file to be checked periodically for size more than zero
  8179. :param should_quit: will quit the app if True; boolean
  8180. :return:
  8181. """
  8182. try:
  8183. if os.stat(filename).st_size > 0:
  8184. self.save_in_progress = False
  8185. self.save_timer.stop()
  8186. if should_quit:
  8187. self.app_quit.emit()
  8188. except Exception:
  8189. traceback.print_exc()
  8190. def save_project_auto(self):
  8191. """
  8192. Called periodically to save the project.
  8193. 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
  8194. # progress.
  8195. :return:
  8196. """
  8197. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8198. self.on_file_saveproject()
  8199. def save_project_auto_update(self):
  8200. """
  8201. Update the auto save time interval value.
  8202. :return:
  8203. """
  8204. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8205. try:
  8206. if self.autosave_timer.isActive():
  8207. self.autosave_timer.stop()
  8208. except Exception:
  8209. pass
  8210. if self.defaults['global_autosave'] is True:
  8211. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8212. self.autosave_timer.start()
  8213. def on_options_app2project(self):
  8214. """
  8215. Callback for Options->Transfer Options->App=>Project. Copies options
  8216. from application defaults to project defaults.
  8217. :return: None
  8218. """
  8219. self.defaults.report_usage("on_options_app2project")
  8220. self.preferencesUiManager.defaults_read_form()
  8221. self.options.update(self.defaults)
  8222. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8223. """
  8224. Shows a message on the FlatCAM Shell
  8225. :param msg: Message to display.
  8226. :param show: Opens the shell.
  8227. :param error: Shows the message as an error.
  8228. :param warning: Shows the message as an warning.
  8229. :param success: Shows the message as an success.
  8230. :param selected: Indicate that something was selected on canvas
  8231. :return: None
  8232. """
  8233. if show:
  8234. self.ui.shell_dock.show()
  8235. try:
  8236. if error:
  8237. self.shell.append_error(msg + "\n")
  8238. elif warning:
  8239. self.shell.append_warning(msg + "\n")
  8240. elif success:
  8241. self.shell.append_success(msg + "\n")
  8242. elif selected:
  8243. self.shell.append_selected(msg + "\n")
  8244. else:
  8245. self.shell.append_output(msg + "\n")
  8246. except AttributeError:
  8247. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8248. class ArgsThread(QtCore.QObject):
  8249. open_signal = pyqtSignal(list)
  8250. start = pyqtSignal()
  8251. stop = pyqtSignal()
  8252. if sys.platform == 'win32':
  8253. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8254. else:
  8255. address = ('/tmp/testipc', 'AF_UNIX')
  8256. def __init__(self):
  8257. super().__init__()
  8258. self.listener = None
  8259. self.thread_exit = False
  8260. self.start.connect(self.run)
  8261. self.stop.connect(self.close_listener)
  8262. def my_loop(self, address):
  8263. try:
  8264. self.listener = Listener(*address)
  8265. while self.thread_exit is False:
  8266. conn = self.listener.accept()
  8267. self.serve(conn)
  8268. except socket.error:
  8269. try:
  8270. conn = Client(*address)
  8271. conn.send(sys.argv)
  8272. conn.send('close')
  8273. # close the current instance only if there are args
  8274. if len(sys.argv) > 1:
  8275. try:
  8276. self.listener.close()
  8277. except Exception:
  8278. pass
  8279. sys.exit()
  8280. except ConnectionRefusedError:
  8281. if sys.platform == 'win32':
  8282. pass
  8283. else:
  8284. os.system('rm /tmp/testipc')
  8285. self.listener = Listener(*address)
  8286. while True:
  8287. conn = self.listener.accept()
  8288. self.serve(conn)
  8289. def serve(self, conn):
  8290. while self.thread_exit is False:
  8291. msg = conn.recv()
  8292. if msg == 'close':
  8293. break
  8294. self.open_signal.emit(msg)
  8295. conn.close()
  8296. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8297. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8298. @pyqtSlot()
  8299. def run(self):
  8300. self.my_loop(self.address)
  8301. @pyqtSlot()
  8302. def close_listener(self):
  8303. self.thread_exit = True
  8304. self.listener.close()
  8305. # end of file